How to print the Results from Google Distance matrix iam Getting a results like this:
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "4,8 km",
"value" : 4820
},
"duration" : {
"text" : "17 minutes",
"value" : 1038
},
"status" : "OK"
},
{
"distance" : {
"text" : "11,1 km",
"value" : 11064
},
"duration" : {
"text" : "25 minutes",
"value" : 1506
},
"status" : "OK"
}
]
}
],
And My Php Code to print The Output is
$json = file_get_contents($url);
$result = json_decode($json, true);
for($i=0; $i<count($result['rows']); $i++) {
echo "Kilometers " . $result['rows'][$i]["elements"][$i]['distance']['text'];
}
.Please Help
Given that you haven't included all the response, the method invlolved in the retrieval of the data nor the final desired output it is tricky to answer but I hope the following will give guidance on how to render the output.
This uses example data from the interwebs rather than the partial example code given in the question - a bit rough perhaps but...
$res='{
"destination_addresses" : [
"Commons Way, Bridgewater, NJ 08807, USA",
"Morris Turnpike, Short Hills, NJ 07078, USA",
"Monmouth Mall, Eatontown, NJ 07724, USA",
"Garden State Plaza Blvd, Paramus, NJ 07652, USA",
"Newport Centre Mall, Jersey City, NJ 07302, USA"
],
"origin_addresses" : [ "75 Ninth Ave, New York, NY 10011, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "68.8 km",
"value" : 68781
},
"duration" : {
"text" : "56 mins",
"value" : 3334
},
"duration_in_traffic" : {
"text" : "1 hour 1 min",
"value" : 3687
},
"status" : "OK"
},
{
"distance" : {
"text" : "34.8 km",
"value" : 34806
},
"duration" : {
"text" : "36 mins",
"value" : 2138
},
"duration_in_traffic" : {
"text" : "41 mins",
"value" : 2487
},
"status" : "OK"
},
{
"distance" : {
"text" : "86.3 km",
"value" : 86322
},
"duration" : {
"text" : "1 hour 6 mins",
"value" : 3930
},
"duration_in_traffic" : {
"text" : "1 hour 7 mins",
"value" : 4044
},
"status" : "OK"
},
{
"distance" : {
"text" : "32.3 km",
"value" : 32278
},
"duration" : {
"text" : "33 mins",
"value" : 2009
},
"duration_in_traffic" : {
"text" : "35 mins",
"value" : 2082
},
"status" : "OK"
},
{
"distance" : {
"text" : "6.9 km",
"value" : 6879
},
"duration" : {
"text" : "19 mins",
"value" : 1113
},
"duration_in_traffic" : {
"text" : "24 mins",
"value" : 1444
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}';
/* return as an object for easier notation */
$json=json_decode( $res, false );
$origins = $json->origin_addresses;
$destinations=$json->destination_addresses;
/* if there are multiple rows, use a loop and `$rows[$i]` etc */
$elements=$json->rows[0]->elements;
foreach( $elements as $i => $obj ){
echo '
<div>
<h5>From: '.$origins[ 0 ].' to '.$destinations[ $i ].'</h5>
Distance: '.$obj->distance->text.',
Duration:'.$obj->duration->text.',
In traffic: '.$obj->duration_in_traffic->text.',
Status: '.$obj->status.'
</div>';
}
Here is an example using a nested foreach, this is not the only way to render the output but it works.
$json = file_get_contents($url);
$result = json_decode($json, true);
foreach ($result['rows'][0] as $elements => $element) {
foreach ($element as $key => $value) {
echo $value['distance']['text'];
echo $value['duration']['text'];
echo $value['status'];
echo '<br>';
}
}
All we are doing is accessing a multi-dimensional array using $key => $value and then $value[$key] notation... I would suggest a crash course on how to handle arrays in php, this one is great: https://www.youtube.com/watch?v=57y5maglayQ
You can also look at the overall structure of your array by writing echo '<pre>', var_dump($result), '</pre>;' which will show your array => key pairs.
Related
Hey guys Im a student and my question might seem simple but i can't find the right answer anywhere. Please take a look. as you can see $parsed_json works fine with this code $parsed_json = $parsed_json['photos']; how do i add another key of the array there? i tried $parsed_json = $parsed_json[(['photos']['contactInfo'])]; but did now work. Any help will much appreciated. Thank you.
<?php
$json_string = file_get_contents("api/goes/here")
$parsed_json = json_decode($json_string, true);
print_r($parsed_json);
$parsed_json = $parsed_json[(['photos']['contactInfo'])];
foreach($parsed_json as $key => $value)
{
echo $value['typeName'] . '<br>';
echo $value['typeId'] . '<br>';
echo $value['familyName'] . '<br>';
// etc
?>
-------------JSON CONTENT------------------------------
{
"status" : 200,
"requestId" : "0ef05ee4-6bab-4488-a80c-04ce050ca074",
"likelihood" : 0.95,
"photos" : [ {
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/651f183b3a1bd463ef5298a2877f2c4f_0c027087db5cd03d244a7dd42e42fc969fa8d636bffd7635b46172c8a597aa73",
"isPrimary" : true
}, {
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/d0080f4ccd9ea21340b0fd994f82c0e0_2acdc7de41111f7d58e7544ed970b78e72f1739784417c146d5689d96ce79137"
} ],
"contactInfo" : {
"familyName" : "Cassini",
"fullName" : "Flavio Cassini",
"givenName" : "Flavio"
},
"organizations" : [ {
"name" : "DEVTECH .LLC",
"startDate" : "2015-03",
"title" : "President/Owner",
"current" : true
} ],
"demographics" : {
"locationDeduced" : {
"normalizedLocation" : "Boca Raton, United States",
"deducedLocation" : "Boca Raton, Florida, United States",
"city" : {
"name" : "Boca Raton"
},
"state" : {
"deduced" : true,
"name" : "Florida",
"code" : "FL"
},
"country" : {
"name" : "United States",
"code" : "US"
},
"continent" : {
"deduced" : true,
"name" : "North America"
},
"county" : {
"deduced" : true,
"name" : "Palm Beach"
},
"likelihood" : 1.0
},
"gender" : "Male",
"locationGeneral" : "Boca Raton, Florida, United States"
},
"socialProfiles" : [ {
"type" : "klout",
"typeId" : "klout",
"typeName" : "Klout",
"url" : "http://klout.com/DevTechServices",
"username" : "DevTechServices",
"id" : "91760869707035580"
}, {
"followers" : 67,
"following" : 67,
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://www.linkedin.com/in/devtechservices",
"username" : "devtechservices",
"id" : "428935547"
}, {
"bio" : "Student at Full Sail University",
"followers" : 5,
"following" : 36,
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://twitter.com/DevTechServices",
"username" : "DevTechServices",
"id" : "3245620291"
} ],
"digitalFootprint" : {
"scores" : [ {
"provider" : "klout",
"type" : "general",
"value" : 48
} ],
"topics" : [ {
"provider" : "klout",
"value" : "Bitcoin"
}, {
"provider" : "klout",
"value" : "Content Marketing"
}, {
"provider" : "klout",
"value" : "SAAS"
}, {
"provider" : "klout",
"value" : "Software"
}, {
"provider" : "klout",
"value" : "WordPress"
} ]
}
}
The short answer is that if $parsed_json represents an associative array of associative arrays, then it stands to reason that $parsed_json['photos'] is an associative array itself. To access the 'contactInfo' value inside it, you simply use $parsed_json['photos']['contactInfo'].
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..
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
I am using the file_get_contents() function in PHP to retrieve the contents on a page containing a JSON response. However, I am struggling to get the "text" data.
$response = file_get_contents(someData)
I can use var_dump(json_decode($response)); to show the data, however, I am trying to get the data from the "text" field only within duration.
So far I have tried
$response[0];
$response->rows[0]->elements[0]->duration[0]->text;
But I cannot seem to get the data. I have pasted the response below
{
"destination_addresses" : [ "Manchester, UK", "Liverpool, Merseyside, UK" ],
"origin_addresses" : [ "London, UK" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "335 km",
"value" : 335444
},
"duration" : {
"text" : "3 hours 36 mins",
"value" : 12955
},
"status" : "OK"
},
{
"distance" : {
"text" : "354 km",
"value" : 354415
},
"duration" : {
"text" : "3 hours 43 mins",
"value" : 13387
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
$response = json_decode(file_get_contents(someData));
$text = $response->rows[0]->elements[0]->duration->text;
var_dump($text);
Your only mistake was a [0] after duration.
i am making a android application n use a .php file to call java script file that returns me a JSON output, now my problem is the output is in a valid JSON format, but i am confused as to how to parse the values. the output is
{
"destination_addresses" : [
"Kambarganvi road, Durgadakeri, Karnataka 580011, India",
"St Inez Road, Santa Inez, Panjim, Goa 403001, India",
"Dr Braganza Pereira Road, Santa Inez, Panjim, Goa 403001, India",
"Dayanand Bandodkar Marg, Santa Inez, Panjim, Goa 403001, India",
"St Inez Road, Santa Inez, Panjim, Goa 403001, India",
"18th June Road, Santa Inez, Panjim, Goa 403001, India"
],
"origin_addresses" : [ "Suyog Residency, St Joaquim Road, Borda, Margao, Goa 403602, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "133 km",
"value" : 132717
},
"duration" : {
"text" : "1 day 4 hours",
"value" : 100199
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.4 km",
"value" : 33427
},
"duration" : {
"text" : "6 hours 54 mins",
"value" : 24832
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33518
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24923
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.8 km",
"value" : 33834
},
"duration" : {
"text" : "7 hours 0 mins",
"value" : 25170
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33503
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24893
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33457
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24880
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
i want to parse the values in such a way that i can place the distances of the result should be put in a data structure like an array and then sort them.
Thank you in advance.
use this to make own model .
http://www.jsonschema2pojo.org/
after making model you can use bwlow code.
Gson gson = new Gson();
gson.fromJson(jData, AddPostModel.class);
AddPostModel have all the data which comes from server.
I'm trying to parse json data from google directions but can't seem to access access any of the values. Here is the php code;
$url = "http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles&sensor=false";
$jsonfile = json_encode(file_get_contents($url));
$jsondata = json_decode($jsonfile);
echo $jsondata->distance;
here is (some) of the json data returns:
{ "routes" : [ { "bounds" : { "northeast" : { "lat" : 41.90085000000001, "lng" : -87.62979000000001 }, "southwest" : { "lat" : 34.052360, "lng" : -118.243560 } }, "copyrights" : "Map data ©2012 Google", "legs" : [ { "distance" : { "text" : "2,015 mi", "value" : 3243390 }, "duration" : { "text" : "1 day 8 hours", "value" : 114318 }, "end_address" : "Los Angeles, CA, USA", "end_location" : { "lat" : 34.052360, "lng" : -118.243560 }, "start_address" : "Chicago, IL, USA", "start_location" : { "lat" : 41.87811000000001, "lng" : -87.62979000000001 }, "steps" : [ { "distance" : { "text" : "0.2 mi", "value" : 269 }, "duration" : { "text" : "1 min", "value" : 34 }, "end_location" : { "lat" : 41.87570, "lng" : -87.62969000000001 }, "html_instructions" : "Head \u003cb\u003esouth\u003c/b\u003e on \u003cb\u003eS Federal St\u003c/b\u003e toward \u003cb\u003eW Van Buren St\u003c/b\u003e", "polyline" : { "points" : "eir~FdezuOhFIF?HAdFG" }, "start_location" : { "lat" : 41.87811000000001, "lng" : -87.62979000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0.2 mi", "value" : 328 }, "duration" : { "text" : "1 min", "value" : 51 }, "end_location" : { "lat" : 41.875680, "lng" : -87.63366000000002 }, "html_instructions" : "Turn \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003eW Congress Pkwy\u003c/b\u003e", "polyline" : { "points" : "czq~FpdzuO?jE#nEBfGAtB" }, "start_location" : { "lat" : 41.87570, "lng" : -87.62969000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "14.0 mi", "value" : 22564 }, "duration" : { "text" : "17 mins", "value" : 1031 }, "end_location" : { "lat" : 41.873870, "lng" : -87.903170 }, "html_instructions" : "Continue onto \u003cb\u003eI-290 W\u003c/b\u003e", "polyline" : { "points" : "_zq~Fj}zuOCtD?fA?f#?pC?P?T#V#zJ?##T?J?J?F?N?#?J?J?N?p##xA?h#?B?~A#xD?h#?lB?n##n#?n#?B#~G?f#A\\EvAGnBEz#EpA?JBlC?F?F?T?B?f#HtM?R?J?t#?|CCvDAb#E`EGlDKzCCd#OrBa#rFGfAAd#?HAp#?`ADbJDzJ?fB?dENdFB~N?d#?RFlH#~C?J#~A?H?XFrKAx##l#?n##^#bANnQ?rAAnMCnC#tH#x#FxJ?hB#tM?j#?p#BxFLrT?B?H?jQBbG#|AHxLBVJ~CLfC\\|EHtAHtAVpDf#tF\\dFTxCXhDVzBNtCFlEB|HBvEDlRAhC?xANxU#^?~A?nADxW#vA?l#Dv[?|#?\\#bCHdI#z#ZxDh#zDRx#T|#t#dCPf#bBlEf#dB^vA^jCR`CDv#?LHfBH`X?z#F|V#pF?`#L|Y#v##dKDbO?jEDdHZjHR`EBd#D`#h#~IHpB#p##n#?p#BjACvFE`IMrIQzIKfEc#tQEjCCn#}#dUSjFCf#mA~[Ar#QlMObGWlEEx#sB`_#Ep#aBt\\EdA?FcAbU?XCrCKnC?zBR|LB`#B\\?Dz#hG#F#Ft#vDJl#pBfMnAtHZ|ERrEJhTH|GLvJ^rHr#|HX`G#`FLnX#`B?`A#|CAbCRnT?BJ`OHrJDbC#r#XzZ?#DfHMdIe#bHIhD#zHPhP?##V#fBN|O?T#j#DnEHpQFlGDtCDtEDrEFlEt#jJF~#`#dDPtAXtCd#`IFlC#j#?j#?hAHpLB~C#bDA|DErBCl#Av#O`C]~DWzB[lB[fB]zAo#dCc#~Am#jBo#bBoCxG?#Sd#g#vAY~#St#W|#_#bBUhAYdB]vBMhA[vCKtAEbAIxA?PAXCb#AhA" }, "start_location" : { "lat" : 41.875680, "lng" : -87.63366000000002 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "140 mi", "value" : 224957 }, "duration" : { "text" : "2 hours 13 mins", "value" : 8008 }, "end_location" : { "lat" : 41.53651000000001, "lng" : -90.32902000000001 }
The error returned is as follows:
( ! ) Notice: Trying to get property of non-object in C:\wamp2\www\phpAcademy\GoogleDirectionsApi\TMP25mnfz82oi.php on line 8
Call Stack
# Time Memory Function Location
1 0.0004 366752 {main}( ) ..\TMP25mnfz82oi.php:0
Google already returns JSON, so you do not need to encode it first. Secondly the 'distance' key is deeper in the response structure:
$origin = "Rome, Italy";
$destination = "Venice, Italy";
$key = "YOUR-OWN-KEY";
$url = "https://maps.googleapis.com/maps/api/directions/json?origin=".urlencode($origin).",IL&destination=" . urlencode( $destination) . "&sensor=false&key=" . $key;
$jsonfile = file_get_contents($url);
$jsondata = json_decode($jsonfile);
echo $jsondata->routes[0]->legs[0]->distance;
You can easily get all the data in json or array format:
$url = "https://maps.googleapis.com/maps/api/directions/json?origin=28.704059,77.102490&destination=30.719059,76.748704&sensor=false";
$jsonfile = file_get_contents($url);
$jsondata = json_decode($jsonfile);
echo $jsondata->routes[0]->legs[0]->distance;
if this error occur:
Catchable fatal error: Object of class stdClass could not be converted to string
than plz use for a output print_r() function