Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Internet (https://www.clubdelphi.com/foros/forumdisplay.php?f=3)
-   -   Obtener latitud y longitud JSON google API (https://www.clubdelphi.com/foros/showthread.php?t=91695)

Alceo 03-04-2017 18:03:14

Obtener latitud y longitud JSON google API
 
Hola a todos,

Tengo semanas tratando de obtener la latitud y longitud de un resultado JSON que me devuelve el API de Google, lo más que podido es obtener el objeto geometry con sus pares, pero sin poder llegar hasta los objetos "lat" y "lng" cualquiera ayuda u orientación es bienvenida:

Código:

{
  "html_attributions" : [],
  "results" : [
      {
        "geometry" : {
            "location" : {
              "lat" : 19.3451341,
              "lng" : -99.18249630000001
            },
            "viewport" : {
              "northeast" : {
                  "lat" : 19.3464830802915,
                  "lng" : -99.1811473197085
              },
              "southwest" : {
                  "lat" : 19.3437851197085,
                  "lng" : -99.18384528029151
              }
            }
        },
        "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
        "id" : "529eb30871b02c0c50608549b3cc580ac7e6b69f",
        "name" : "Walmart Taxqueña",
        "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
        },
        "photos" : [
            {
              "height" : 1836,
              "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/113641325266025078503/photos\"\u003eEdwin Pineda\u003c/a\u003e"
              ],
              "photo_reference" : "CoQBdwAAAIwcR5DJ1J1suk4BkWQeux0mafZL2GA8slkvY-6mcntCZMg4tRR4WEZtNI1ZtUIp_bPGwSKuV_xPU8CbSRgROqUtjQdbtHzIsOA2jxNuNaaDgSPKRGdqzR3FHtENPGulEWn6H0K1FNoBw3tDTpXUNYThpPkagrh0_CmfSFQiAtvBEhD8Bl-nTm6urxljqSyi8C-tGhR__Qzvcc6Abr9sKY8O-UMcDCWCfw",
              "width" : 3264
            }
        ],
        "place_id" : "ChIJkbeg_fn_0YURW1FIsXJ8vOY",
        "price_level" : 1,
        "rating" : 3.9,
        "reference" : "CmRSAAAA_Ce9o5AGWtDD7EAEUKYPI8yDWxV32Ii7ixu6rRXiWPpqJTABq_LZdWmXuwgh6As3ARbKIVPipLysgjxZ8xvUe2KxKxZItytznGsWFueJYDMxEUHIQJQ1pnxujo0Y5OclEhDxw9IMlVtzcAyYLT9msPCMGhSc0ZcFusw0y3m41bVrGAbPtBYGAQ",
        "scope" : "GOOGLE",
        "types" : [
            "grocery_or_supermarket",
            "food",
            "store",
            "point_of_interest",
            "establishment"
        ],
        "vicinity" : "Miguel Ángel de Quevedo 175, Chimalistac, Álvaro Obregón"
      },
      {
        "geometry" : {
            "location" : {
              "lat" : 19.337697,
              "lng" : -99.1840301
            },
            "viewport" : {
              "northeast" : {
                  "lat" : 19.3389653302915,
                  "lng" : -99.1826781197085
              },
              "southwest" : {
                  "lat" : 19.3362673697085,
                  "lng" : -99.1853760802915
              }
            }
        },
        "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
        "id" : "6fcf72ad6f1e78e089f17c4a153d61f054edeb41",
        "name" : "Walmart Copilco",
        "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
        },
        "photos" : [
            {
              "height" : 2988,
              "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/117301581838698298835/photos\"\u003esalvador pelayo\u003c/a\u003e"
              ],
              "photo_reference" : "CoQBdwAAABn2W8YIJSZh86TeAdNfja54ooB2Qe8wvYlyYorqFshmat_qPVD_sk8_r9miu1qxFJSdQ3d9wM-oyvhYf1mCXiQsCK_BflvSg0ZlvnMWypHEjJLHOvYULW5l5XiYBwXw0P9AIkzTII0T9FoDa4Y3LJVktd-jBVx68aVr95CVYCdIEhC2GspgQFh_XVFmoTRN7C_1GhSBlF54BwQ-Hj_3EJ1kYxnmE-JVgQ",
              "width" : 5312
            }
        ],
        "place_id" : "ChIJCVX93f3_0YUR89VBpPan3Hg",
        "price_level" : 1,
        "rating" : 3.9,
        "reference" : "CmRRAAAA7blwyY8q-sY7dRNMnPF5VMWQBYPCuxMm0H28DcthQ15edLrVFU0o84_nz5EjtNvFW4_BSiIZ2OnsUd5RxJmOuyQNQeD2P1xx-Xb9-F6uobhSNI3x4nRGMBFXqEJMZFJIEhAwvyoU2Emth0Ezo_OzfBWhGhQXWP3RiNHK0MxEVVt52Bbsu3_APQ",
        "scope" : "GOOGLE",
        "types" : [
            "grocery_or_supermarket",
            "food",
            "store",
            "point_of_interest",
            "establishment"
        ],
        "vicinity" : "Avenida Copilco 164, Coyoacán, Ciudad de México"
      },
      {
        "geometry" : {
            "location" : {
              "lat" : 19.352804,
              "lng" : -99.21554359999999
            },
            "viewport" : {
              "northeast" : {
                  "lat" : 19.3541529802915,
                  "lng" : -99.21419461970849
              },
              "southwest" : {
                  "lat" : 19.3514550197085,
                  "lng" : -99.2168925802915
              }
            }
        },
        "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
        "id" : "d159183a063e3505e11c5d459b50817ac32e99e6",
        "name" : "Walmart Las Águilas",
        "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
        },
        "photos" : [
            {
              "height" : 2208,
              "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/103757958472199504313/photos\"\u003eNOE OROZCO\u003c/a\u003e"
              ],
              "photo_reference" : "CoQBdwAAAE_z0SVjjuSGuCWzK91mBUYvxhcRY2q3p9YuQ-oi-rwgInLocRO94Bcv4fiA-_Zsw-xZbNzCrPTFZ4aOuKWEyggsEvUxlUBCVUV8P-SbR7vtNKEgBR_UhR6bO2LyvvBj-LnH9gfSc09wzUYnDijrHWCpMiH5ADoKo3WlNl0z7WBEEhDl9GTNIj8A0NduWdsl2tnHGhQilLlTiwlQaCmgTjsdH35pUjL5hw",
              "width" : 3920
            }
        ],
        "place_id" : "ChIJESlbhWsA0oUR9QoVBs4Atqw",
        "price_level" : 1,
        "rating" : 3.9,
        "reference" : "CmRSAAAAxslVH4TIlvLLUQipU9F_3XJUA9FpowoWen7E_tBOydgh3AdKebTffSeX-26lauzFM555liDohjXa56he4vYdtSl8NCC58LIVV-Xak34k4GlsRA-y8xY90C9ceIS8-fFwEhD5q5cqcEJF_KA3ukJJNR5fGhQhogHZaScm7vhwnrcDSAlujowBog",
        "scope" : "GOOGLE",
        "types" : [
            "grocery_or_supermarket",
            "food",
            "store",
            "point_of_interest",
            "establishment"
        ],
        "vicinity" : "Calzada de Las Aguilas 820, Las Aguilas, Álvaro Obregón"
      },
      {
        "geometry" : {
            "location" : {
              "lat" : 19.3607243,
              "lng" : -99.18963970000001
            },
            "viewport" : {
              "northeast" : {
                  "lat" : 19.3620622302915,
                  "lng" : -99.1881842697085
              },
              "southwest" : {
                  "lat" : 19.35936426970849,
                  "lng" : -99.19088223029151
              }
            }
        },
        "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
        "id" : "1d2386ee5649d707654dee76174b1112e02e4075",
        "name" : "Plaza Walmart",
        "photos" : [
            {
              "height" : 4160,
              "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/100289534035202124841/photos\"\u003eJuan Uribe\u003c/a\u003e"
              ],
              "photo_reference" : "CoQBdwAAAB6p7oa-tCUdf46YSzs0ToKyIhYHB1fLY-E0SPm1HtNnWhnn2TcFfMlReFAb6jigq6zTTdSTfTMU9Nnwj82st5UVreHPNzXLjLE_H1-begpGKx-h2wIsLkN113THF2BfnLIwg2Ec60CL0Xlpoaos-jm4dAM4M-ZQC1xmSaU5J9zDEhBULtD_h-E7cK7FFPZUOpNMGhR61TFBJWm9r5t6eFYq8Nh9uHkawg",
              "width" : 2336
            }
        ],
        "place_id" : "ChIJt7Vppor_0YUR_-AeyE7I93w",
        "price_level" : 1,
        "rating" : 4,
        "reference" : "CmRRAAAAkjL00qk-_zpry8dYHW8TMYtUTe3WEciMWcEtwoGAM_lRyw_DbpV3wBwpKZoXe3cg5w0-wu5bco4w3dEGJjYljYpPlgUqe8kp5TlNkonVVQ71hP4mSx3G0MhsdlLP_TJOEhA7GRjqRhRhOb0n2fT5u99fGhRv77rF12tLI47hXLMG_EABbXqxiQ",
        "scope" : "GOOGLE",
        "types" : [ "shopping_mall", "point_of_interest", "establishment" ],
        "vicinity" : "01010, Avenida Revolución 1267, Los Alpes"
      }
  ],
  "status" : "OK"
}

Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
var
  s: string;
  LJsonObj: TJSONObject;
  blh: TJSONObject;
  geometry, location: TJSONObject;
  rate: String;
  jValue : TJSONValue;
  jPair : TJSONPair;
  jArray : TJSONArray;
  i : integer;

begin
   s := TFile.ReadAllText('D:\503890\Mis documentos\Embarcadero\Studio\Projects\GetJsonValue\walmart.txt');
  jValue := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(s), 0);
  try
    LJsonObj := jValue as TJSONObject;

    jPair := LJsonObj.Get('results');
    jArray := jPair.JsonValue as TJSONArray;
    for i := 0 to jArray.Size - 1 do
    begin
      showmessage('elemento '+InttoStr(i));

      geometry := jArray.Get(i) as TJsonObject;

      for jPair in geometry do
      begin
        showmessage('   '+jPair.JsonString.Value+': '+jPair.JsonValue.Value);
      end;
    end;

  finally
    jValue.Free;
  end;
end;

MAXIUM 03-04-2017 21:35:51

La verdad es que no se de esto, pero encontré esta web con excelentes ejemplos: https://theroadtodelphi.com/2015/10/...-desktop-apps/ al pie aparecen más detalles.

El autor es de habla hispana pese a que la web es en ingles por si quieres hacerle consultas.

AgustinOrtu 03-04-2017 22:29:45

Podes probar de esta manera:

Código Delphi [-]
uses
  System.IOUtils,
  System.JSON,
  System.SysUtils;

procedure DoIt;
var
  json, geometry, location: TJSONObject;
  results: TJSONArray;
  lat, lng: TJSONNumber;
  I: Integer;
begin
  json := TJSONObject.ParseJSONValue(TFile.ReadAllText(JsonFile)) as TJSONObject;

  try
    results := json.Values['results'] as TJSONArray;   
    geometry := results.Items[0].GetValue('geometry');
    location := geometry.Values['location'] as TJSONObject;
    lat := location.Values['lat'] as TJSONNumber;
    lng := location.Values['lng'] as TJSONNumber;
    Writeln(lat.ToString);
    Writeln(lng.ToString);
  finally
    json.Free;
  end;
end;

Tene en cuenta que no hago ninguna validacion sobre la estructura del json, y asumo que el primer elemento del array "results" es el "geometry"

WHILENOTEOF 03-04-2017 23:01:49

Cita:

Empezado por AgustinOrtu (Mensaje 515094)
Podes probar de esta manera:

Código Delphi [-]
uses
  System.IOUtils,
  System.JSON,
  System.SysUtils;

procedure DoIt;
var
  json, geometry, location: TJSONObject;
  results: TJSONArray;
  lat, lng: TJSONNumber;
  I: Integer;
begin
  json := TJSONObject.ParseJSONValue(TFile.ReadAllText(JsonFile)) as TJSONObject;

  try
    results := json.Values['results'] as TJSONArray;   
    geometry := results.Items[0].GetValue('geometry');
    location := geometry.Values['location'] as TJSONObject;
    lat := location.Values['lat'] as TJSONNumber;
    lng := location.Values['lng'] as TJSONNumber;
    Writeln(lat.ToString);
    Writeln(lng.ToString);
  finally
    json.Free;
  end;
end;

Tene en cuenta que no hago ninguna validacion sobre la estructura del json, y asumo que el primer elemento del array "results" es el "geometry"

Con Delphi Seattle el texto marcado me da error. Cambiando por el texto siguiente me funciona bien:

Código Delphi [-]
   s:= TFile.ReadAllText(OpenDialogJson.FileName);
   jValue:= TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(s), 0);
    try
      LJsonObj:= jValue as TJSONObject;

      jPair:= LJsonObj.Get('results');
      jArray:= jPair.JsonValue as TJSONArray;
      for i:= 0 to jArray.Size - 1 do
       begin
        jArray.Items[i].TryGetValue('geometry',geometry);
        location := geometry.Values['location'] as TJSONObject;
        lat:= location.Values['lat'] as TJSONNumber;
        lng:= location.Values['lng'] as TJSONNumber;
       end;

    finally
      jValue.Free;
    end;

AgustinOrtu 03-04-2017 23:49:48

Ah ya veo cual es el problema, es que el metodo TJSONValue.GetValue utiliza tipos genericos y yo publique el codigo usando el resaltador de sintaxis de Delphi, al cual no le gustan los genericos :p

Ahora si

Código PHP:

var
  
jsongeometrylocationTJSONObject;
  
resultsTJSONArray;
  
latlngTJSONNumber;
begin
  json 
:= TJSONObject.ParseJSONValue(TFile.ReadAllText(JsonFile)) as TJSONObject;

  try
    
results := json.Values['results'] as TJSONArray;
    
geometry := results.Items[0].GetValue<TJSONObject>('geometry');
    
location := geometry.Values['location'] as TJSONObject;
    
lat := location.Values['lat'] as TJSONNumber;
    
lng := location.Values['lng'] as TJSONNumber;
    
Writeln(lat.ToString);
    
Writeln(lng.ToString);
  
finally
    json
.Free;
  
end



La franja horaria es GMT +2. Ahora son las 16:55:03.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi