0

how to parse JSON google maps JSON in php

i have do it in xml, but the coordinates driving direction's not complete as i get with JSON, how we can get all coordinate driving with JSON in php?

if we do using xml

$xml = simplexml_load_file('http://maps.googleapis.com/maps/api/directions/xml?origin='.$origin.'&destination='.$dest.'&sensor=false');
$startlat = $xml->xpath("/DirectionsResponse/route/leg/step/start_location/lat");
$startlng = $xml->xpath("/DirectionsResponse/route/leg/step/start_location/lng");
$distanceeach = $xml->xpath("/DirectionsResponse/route/leg/step/distance/value");
$distance = $xml->xpath("/DirectionsResponse/route/leg/distance/value");

but how to do with json? and i want my variable $startlat, $startlng, etc, contains same value if we do with xml

1 Answer 1

1

You can retrieve data in JSON format, and then use json_decode() function to build stdClass object, then you can recursively walk through object's property to convert it into (array) $response as this.

And then use Google Maps API response as an array. You can proceed with no converting to array, and use object of stdClass like this:

$response->DirectionsResponse->route->leg->step->start_location->lat;

To get the correct values you can always var_dump() you response object, and see what you want to get.

Hope, that helps.


Here is the code for usage Google JSON response from Google Translate API... which is much the same, as you need:

if (!is_null($json = json_decode(file_get_contents($url)))
{
    return $json->data->translations[0]->translatedText;
}

That's it...

Sign up to request clarification or add additional context in comments.

1 Comment

hai @devdRew can you give me complete code? i'm stuck right here :(

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.