Newb having trouble with simple task of querying Google Maps for the distance between two cities. Really, a first learning attempt to get JSON data and make use of it.
I googled a ton, and read many related answers here on SO, first. (Though I eventually found the main answer here.)
I pasted all the code, along with comments about what I was thinking, hoping that someone could explain what I was missing, in beginner terms.
The main problem is that I'm getting the data with one of the two methods I tried ($.ajax, but not $.getJSON, though I thought both would work), see Console Output at the very end of the code, but I couldn't figure out how to actually grab/use the data. Specifically, in the multi-nested object/array combo, I was trying to get the "text" in "distance" in "legs" in "routes" in the "responseText" that was returned.
[edit:] Ok, I finally found an existing SO question, that was [enough to figure it out] (How can I get the object in JSON using jquery or javascript)
In hindsight, I should have just kept looking through even more existing answers.
I'm not sure whether to leave, delete or erase, but I'll edit a bit and leave for now, because there are still parts of the question that are confusing, including:
- How to use $.getJSON, in the code below -- shouldn't that work, too?
- How to know exactly what part of the overall JSON object to use as the argument in the $.parseJSON() method;
Why you still have to use $.parseJSON if you can see your object outputted, and it looks like the object/array combination already. See comments, below.
<!DOCTYPE html> <html> <head> <title>City Distances</title> <script src="js/jquery.min.js"></script> </head> <body> <input type="text" id="city1" value="Atlanta"><br/> <input type="text" id="city2" value="Orlando"><br/> <button type="submit" id="btn">Submit</button> <script> var city1 = document.getElementById('city1'); var city2 = document.getElementById('city2'); var btn = document.getElementById('btn'); var valCities = []; function getCities () { valCities[0] = city1.value; valCities[1] = city2.value; var gMap = "http://maps.googleapis.com/maps/api/directions/json?origin=" + valCities[0] + "&destination=" + valCities[1] + "&sensor=false"; // I'm confused about what $.getJSON is supposed to get. // Here's why I was trying to get the JSON data. I never saw how this would work; no idea. var b = $.getJSON(gMap); // Is the data I'm looking for in here, somewhere? // I thought there'd be something like the c['responseText'], below. // (I numbered each element (g), b/c I thought I could access with [#] bracket notation). var g = 0; for (var i in b) { console.log("$.getJSON: <" + g + "> [" + i + "]: " + b[i]); g += 1; }; // jQuery method (I found more examples that used this method, so I tried this, too.) // I'm confused by the example showing the argument 'json' being passed in, b/c I didn't // use it. // But c['responseText'] seemed to have the "distance" data I needed. var c = $.ajax({ type: "GET", url: gMap, dataType: "json", success: function(json) { // I'm trying to see what was gotten. Added counter for the elements; I // thought maybe I could access with bracket notation using the number of // the element. // The relevant output is listed, below, in comment at end of script. console.log("\n $.ajax success: \n") var h = 0; for (var j in c) { console.log("$.ajax: <" + h + "> c[" + j + "]: " + c[j]); h += 1; }
** This is what finally worked **
// nested objects and arrays...
var d = c['responseText'];
var jsonObject = $.parseJSON(d);
var theDistance = jsonObject.routes[0].legs[0].distance.text;
console.log("*** theDistance: " + theDistance + "\n\n ***");
Or was it that I should use .map like this?
Anyway, here's the the rest, mostly just for the console.log output at the end:
// **And if this works, and prints out all the data:
var d = c['responseText']; // (from above)
console.log("ddd: " + d);
/* This is what it prints to the console:
ddd: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
"text" : "442 mi",
"value" : 710661
},
*/
// **Then why doesn't this work? (It says routes is undefined.)
console.log(d.routes[0].legs[0].distance.text);
}
});
}
// Event handler for the little form (which already has the two demo cities, pre-populated.
btn.addEventListener("click", getCities, false);
/*
** OUTPUT **
This is the relevant JSON data returned from Google from the console.log, above.
[Console output:]
. . .
$.ajax: <18> c[responseText]: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
** --- This is what I was trying to get --- **
**"text" : "442 mi",**
"value" : 710661
},
"duration" : {
"text" : "6 hours 13 mins",
"value" : 22360
},
"end_address" : "Orlando, FL, USA",
"end_location" : {
"lat" : 28.53831440,
"lng" : -81.37924350
},
"start_address" : "Atlanta, GA, USA",
"start_location" : {
"lat" : 33.74883970,
"lng" : -84.38750639999999
*/
</script>
</body>
</html>