Reputation: 5
I'm having trouble correctly accessing data in Google Maps API php.
Heres what example data looks in php:
{"destination_addresses":["Destination address"],"origin_addresses":["Origin address"],"rows":[{"elements":[{"distance":{"text":"3.3 km","value":3314},"duration":{"text":"6 mins","value":334},"status":"OK"}]}],"status":"OK"}
Heres my .js:
$(function(){
$("#button").click(function(){
var start = $("#start").val(); //gets start and end values from input fields, and passes them to .php which is not visible here.
var end = $("#end").val();
$.ajax({url: "googlemaps.php",
method: "GET",
data : { "start" : start, "end" : end },
success: function(result) {
print(result);
},
error: function(xhr){
alert("Error: " + xhr.status + " " + xhr.statusText);
}
});
});
});
function print(result){
var length = "";
for(var i = 0;i < result.rows.length;i++){
length += result.rows[i].text+ "<br/>";
$("#div").html(length);
}}
It should calculate the distance between two addresses, and it currently returns unidentified (which is ok), since
length += result.rows[i].text+ "<br/>";
is not correct. I have no idea how to access value "text":"3.3 km", or it's equivalent in my code. I know it is an object inside "distance", which is an array item of "elements", which is an array item of "rows".
Upvotes: 0
Views: 162
Reputation: 2359
If your array is result
, then you can access the distance by using this:
var distance = result['rows'][0]['elements'][0]['distance']['text'];
Upvotes: 0
Reputation: 115
Its structured like:
rows[0].elements[0].distance.text
You might not need the loop, but if you were to use it you would do something like.
for (var i = 0;i < result.rows.length; i++) {
for (var k = 0;k < result.rows[i].elements.length; k++) {
length += result.rows[i].elements[k].distance.text + "<br/>";
}
}
$("#div").html(length);
Upvotes: 1