1

I am trying to get the lat/lng of an address with the Google maps API. I am having trouble parsing the JSON result just to store the lat and lng values as PHP variables. Anyone able to help me parse this?

This is what I have so far:

<?php

$jsonObject = file_get_contents(
"http://maps.googleapis.com/maps/api/geocode/json?
address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true");

$object = json_decode($jsonObject);

$lat = $object->results[0]->geometry[0]->location[0]->lat;
$lng = $object->results[0]->geometry[0]->location[0]->lng;

echo "$lat, $lng";

?>

This is the JSON feed (the lat/lng values are about two-thirds the way down the code):

  {
"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara",
           "short_name" : "Santa Clara",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4216410,
           "lng" : -122.08550160
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.42298998029150,
              "lng" : -122.0841526197085
           },
           "southwest" : {
              "lat" : 37.42029201970850,
              "lng" : -122.0868505802915
           }
        }
     },
     "types" : [ "street_address" ]
  }
],
"status" : "OK"
}

1 Answer 1

3

geometry and location aren't arrays, try

$lat = $object->results[0]->geometry->location->lat;
$lng = $object->results[0]->geometry->location->lng;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Musa. You nailed it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.