I’m trying to build in jQuery mobile a simple "store location" service, where in one screen, a make a list of all stores and show the distance from current position, using Google maps API.
I was looking at this example:
http://code.google.com/apis/maps/documentation/javascript/examples/distance-matrix.html
from which I was using the following code:
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += origins[i] + " to " + destinations[j]
+ ": " + results[j].distance.text + " in "
+ results[j].duration.text + "<br />";
}
}
}
}
It works OK, as it populates the #outputDiv with the information needed.
Now, I’m stuck on how to use calculateDistances(), to populate each div where it belongs to each store! I’m not understanding how to return the results of above function since the callback() already defines var outputDiv = document.getElementById('outputDiv'); which for now only works on 1 div…
What do I need to do in order to each time I call calculateDistances(), it populates the div I want to?
The simplest way would be to use the corresponding divs inside the loop, instead of appending all output to the innerHTML of the same div. So in your loop in the callback you can have something like this:
This will put the results for each pair [i, j] of origins and destinations into a separate div with ID
outputDiv_i_j, for exampleoutputDiv_1_3.The other alternative would be to stick the results into an array – and then output the values from the array to whatever div’s you like:
After this, you can do whatever you like with your array.