-1

I want to get the schools near to a set of locations

So I put that places search in loop. The search function has a callback function which returns me the result. But the callbacks are executed in random and not in the order in which I requested . So I am unable to know which school was returned for which place???

for(i in array_of_loc)
service.nearbySearch({
location: array_of_loc[i],
rankBy:google.maps.places.RankBy.DISTANCE,
types: ['school']
}, function callback(results, status) {
alert(i);
//get the result to get info of places returned and assign it to requested location });

The alert always gives me the the length of array. That is the callbacks are called after the loop has finished. So I don't no which pace is for which location

NIMISHAN
  • 1,265
  • 4
  • 20
  • 29
Balaji
  • 35
  • 11

1 Answers1

1

You should make a function to search, that way you create a closure where location is always reachable, even after the callback. Plus you shouldn't use for (... in ...) loop to iterate over an array :

function search (location) {
    service.nearbySearch({
        location: location,
        rankBy: google.maps.places.RankBy.DISTANCE,
        types: ['school']
    }, function callback(results, status) {
        alert(location);
    });
}

for(var i = 0; i < array_of_loc.length; i++) {
    search(array_of_log[i]);
}
Community
  • 1
  • 1
Serge K.
  • 5,303
  • 1
  • 20
  • 27