I'm trying to plot lines between two or more addresses in Google Maps. The idea is that addresses are in an array (in the order of the route taken), then the array is looped over and geocoded via Google Maps, so I then have an array of co-ordinates:
function showRoute(routes) {
var points = [];
var geocoder = new GClientGeocoder();
for (var i = 0; i < routes.length; i++) {
geocoder.getLatLng(routes[i], function(point) {
points.push(point);
drawRoute(points, routes);
});
}
}
The drawRoute() function will only run through if the array passed to it is the same as the length of the original routes array.
Most of the time this works fine. However, it will break if there's a lag in getting a response from the geocoder for any value, as it'll result in them being out of order.
My first attempt around this problem was as follows:
function showRoute(routes) {
var points = [];
var geocoder = new GClientGeocoder();
for (var i = 0; i < routes.length; i++) {
geocoder.getLatLng(routes[i], function(point) {
points[i] = point;
drawRoute(points, routes);
});
}
}
But as the function runs asynchronously, it means that the value of i inside the geocode callback is always going to be the length of the routes array, so it'll just keep overwriting the same value.
Anyone got any ideas?