I am using the following code to pull some mileage data from Google Maps Distance Matrix. The problem is it comes back as plain javascript. I have managed to get it to put the data into a javascript array, so I have :
arrResults[0]
arrResults[1]
arrResults[2]
arrResults[3]
But I want to use the array in Jquery now, but cant work out how to convert it into a Jquery array ?.
$( document ).ready(function() {
$( "#submit" ).click(function() {
$("#my_map").gmap3({
getdistance:{
options:{
origins:["pe219px","ng323rj"],
destinations:["pe219px","ng323rj"],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
},
callback: function(results, status){
var html = "";
var arrResults = [];
if (results){
for (var i = 0; i < results.rows.length; i++){
var elements = results.rows[i].elements;
for(var j=0; j<elements.length; j++){
switch(elements[j].status){
case "OK":
var sd=$(this).text();
html += parseInt(elements[j].distance.text) + "<br />";
arrResults.push(elements[j].distance.text);
break;
case "NOT_FOUND":
html += "The origin and/or destination of this pairing could not be geocoded<br />";
break;
case "ZERO_RESULTS":
html += "No route could be found between the origin and destination.<br />";
break;
}
}
}
} else {
html = "error";
}
$("#my_map").html( html );
}
}
});
}); });
</head>
<body>
<div id="my_map"></div>
<p><a id="submit" href="#">Submit</a></p>
It slightly more problematic because you're using the
gmap3
plugin, but here's how I would approach the problem.First: redacted (see edits for more details)
Second, make
arrResults
available globally to your functions by declaring it at the top of the IIFE. Don't redeclare it anywhere else.Third, separate out your callback logic from the ajax function into a new function. It makes the code easier to read. Something like
processData()
.Third, once the AJAX is done and your
processData
function has finished its run-through, usejQuery
to add a new#viewresults
button to your page.You do this because AJAX is
asyncronous
. Clicking theviewresults
button before the data has been collected would result in either an error or nothing, so it makes sense (for your code at least) to have the button only available once the data is available.I've provided a summary of these thoughts in this jsfiddle (untested, but should give you a few clues). I hope you find it useful.