Reputation: 165
I'm trying to filter out addresses on a Google map based on driving/walking duration. However, it seems like I'm missing something really basic in how this Javascript snippet runs:
//addresses that I'd like to compare to a point of origin
var addresses = ['address_1','address_2','address_3','address_4','address_5'];
//point of interest/origin
var origin = 'origin_address';
for (i=0;i<addresses.length;i++){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var request = {
origin: origin,
destination: addresses[i],
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//====> Why can't I access results[i] here? I get "undefined" for the following
alert(addresses[i]);
// I get 3 identical values, then a unique fourth value
alert(response.routes[0].legs[0].duration.value);
//if the duration is below a certain value, I'd like to show a marker.
//however, I can't do that, since I can't access addresses[i]
if(response.routes[0].legs[0].duration.value < 1200){
//Geocode address & show marker
}
}
});
}
Any idea why: 1) I can't access the variable "addresses" from inside: directionsService.route(request, function(response, status) { //.....HERE..... });
2) Is this the right way to compare durations for different routes, or am I doing something seriously inefficient?
Thanks a lot!
Upvotes: 2
Views: 391
Reputation: 82594
That function is a callback function. Its scope is different fro. what you might think it is. In that function, i doesn't exist.
My phone is really bad for SO, but Your response variable will have the address you are looking for from you request variable.
EDIT
You can try closures:
directionsService.route(request, (function (address) {
return function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//====> Why can't I access results[i] here? I get "undefined" for the following
alert(address);
// I get 3 identical values, then a unique fourth value
alert(response.routes[0].legs[0].duration.value);
//if the duration is below a certain value, I'd like to show a marker.
//however, I can't do that, since I can't access addresses[i]
if(response.routes[0].legs[0].duration.value < 1200){
//Geocode address & show marker
}
})(addresses[i])
});
Upvotes: 2