I am currently working on a project that involves plotting lines between multiple addresses using Google Maps. The approach is to store the addresses in an array (in the order of the route taken), then looping over the array and geocoding them through Google Maps to obtain an array of coordinates:
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 execute if the length of the array passed to it matches the original routes array.
While this method generally works well, it can encounter issues if there is a delay in receiving responses from the geocoder, resulting in the coordinates being out of order.
To address this issue, my initial solution 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);
});
}
}
However, due to the asynchronous nature of the function, the value of i within the geocode callback will always be equal to the length of the routes array, causing it to overwrite the same value repeatedly.
Does anyone have any alternative suggestions?