首页 文章

在PHP中获取Google Maps api

提问于
浏览
-2

我现在需要使用PHP解码以下json(https://maps.googleapis.com/maps/api/geocode/json?address=via%20pascal%2033/2%2042123%20reggio%20emilia&key=)的位置lat和lng,并将这两个数据检索为vars:

{
"results" : [
  {
     "address_components" : [
        {
           "long_name" : "2",
           "short_name" : "2",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Via Blaise Pascal",
           "short_name" : "Via Blaise Pascal",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Reggio Emilia",
           "short_name" : "Reggio Emilia",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Reggio nell'Emilia",
           "short_name" : "Reggio nell'Emilia",
           "types" : [ "administrative_area_level_3", "political" ]
        },
        {
           "long_name" : "Provincia di Reggio Emilia",
           "short_name" : "RE",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "Emilia-Romagna",
           "short_name" : "Emilia-Romagna",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "Italia",
           "short_name" : "IT",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "42123",
           "short_name" : "42123",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "Via Blaise Pascal, 2, 42123 Reggio Emilia RE, 
Italia",
     "geometry" : {
        "location" : {
           "lat" : 44.6666003,
           "lng" : 10.5960504
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 44.6679492802915,
              "lng" : 10.5973993802915
           },
           "southwest" : {
              "lat" : 44.6652513197085,
              "lng" : 10.5947014197085
           }
        }
     },
     "partial_match" : true,
     "place_id" : "ChIJWaiGeqUcgEcR9l6qwloEWgo",
     "types" : [ "street_address" ]
  }
],
"status" : "OK"
}

最后,我需要的是能够向用户显示:

“纬度为$ lat,经度为$ lng”

谢谢

1 回答

  • -1

    如果您只需要最后的结果点,请尝试使用此代码 .

    $myJsonData = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=via%20pascal%2033/2%2042123%20reggio%20emilia&key=");
    $myArrayData = json_decode($myJsonData, 1);
    foreach($myArrayData['results'] as $myItem){    
    $lat = $myItem['geometry']['location']['lat'];
    $lng = $myItem['geometry']['location']['lng'];
    }
    printf("Latitude is %s and longitude is %s", $lat, $lng);
    

相关问题