0

I have one array

SchoolAddress[0] = Abelsvej 98, 4100, Ringsted;
SchoolAddress[1] = Prstevej 19, 4100, Ringsted;
SchoolAddress[2] = Haraldsvej 77, 4100, Ringsted;

I have to get latitude & longitude for this address.

I am using google geocoder for this.

for (var i = 0; i < schools.length; i++) 
{
    var address = schools[i][1];
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address }, function (results, status) 
    {
        var location = results[0].geometry.location;
        schoolslat[i] = location.lat() + ', ' + location.lng();
    });
} 

Here what happens is as call takes some time, the values coming from call do not go to proper schoolslat[i].

fedosov
  • 1,989
  • 15
  • 26
vaibhav shah
  • 4,939
  • 19
  • 58
  • 96

1 Answers1

3

You may use closure to freeze variable i in your request:

for (var i = 0; i < schools.length; i++) 
{
    (function(i){
        var address = schools[i];
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': address }, function (results, status) 
        {
            var location = results[0].geometry.location;
            schoolslat[i] = location.lat() + ', ' + location.lng();
        });
    }(i));
}

UPD:

JSFiddle example.

Community
  • 1
  • 1
fedosov
  • 1,989
  • 15
  • 26
  • Can you provide array content of `schools`? – fedosov Apr 13 '13 at 10:06
  • my array is [Abelsvej 98, 4100, Ringsted], [Almstoftevej 71, 4100, Ringsted], [Balstrupvej 35, 4100, Ringsted], [Ejlstrupvej 101, 4100, Ringsted], [Ejlstrupvej 101 C 101, 4100, Ringsted], [Ejlstrupvej 90 90, 4100, Ringsted], [Haraldsvej 7 7, 4100, Ringsted], [Løngangen 43 65, 4100, Ringsted], [Vetterslev Bygade 21 21, 4100, Ringsted], [Østergade 25, Høm 25, 4100, Ringsted], [Østergade 3, høm 3, 4100, Ringsted] – vaibhav shah Apr 13 '13 at 10:15
  • In that case `schools[i][1]` always gives you the second character of an address as a search term, so you searching for `b`, `l`, `a`, `j` etc. – fedosov Apr 13 '13 at 10:26
  • I fixed this example http://jsfiddle.net/fedosov/Ypf8v/10/ (missing semicolon). But you must provide some timeout between requests, otherwise you get `OVER_QUERY_LIMIT` error. – fedosov Apr 13 '13 at 10:44
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/28152/discussion-between-fedosov-and-vaibhav-shah) – fedosov Apr 13 '13 at 10:45
  • Can we do something so that script will go to further process only after receiving these values – vaibhav shah Apr 13 '13 at 11:57
  • @vaibhavshah yes, you can use callback for example. – fedosov Apr 13 '13 at 12:19
  • After each request you can check whether all adresses already found and fire the callback if true. – fedosov Apr 13 '13 at 14:08