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].

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Can you provide array content of schools?
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]
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.
I fixed this example jsfiddle.net/fedosov/Ypf8v/10 (missing semicolon). But you must provide some timeout between requests, otherwise you get OVER_QUERY_LIMIT error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.