Karthik CP Karthik CP - 3 months ago 7
jQuery Question

Parse JSONArray in Jquery

I am Creating a webapp where i could get the distance and time of travel using google map API..

https://maps.googleapis.com/maps/api/distancematrix/json?origins=10.964,76.007&destinations=10.982,75.999


I am using HTTP method as given by google..
Its returning JSON Format as give below

{
"destination_addresses" : [ "Kanyakumari - Panvel Highway, Palathara, Kerala 676501, India" ],
"origin_addresses" : [ "Kanyakumari - Panvel Highway, Randathani, Kerala 676510, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "2.5 km",
"value" : 2526
},
"duration" : {
"text" : "4 mins",
"value" : 228
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}


How could i extract the distance text and duration text using jquery and alert it..

Answer

Use file_get_contents() and json_decode() the output..

$contents = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=10.964,76.007&destinations=10.982,75.999');
$data = json_decode($contents,true);
echo 'Distance : '.$data['rows'][0]['elements'][0]['distance']['text'];
echo "<br>";
echo 'Duration : '.$data['rows'][0]['elements'][0]['duration']['text'];

This will give you :

Distance : 2.5 km
Duration : 4 mins