GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?

asynchronous, geocode, google-maps, javascript

Solution

The simplest thing is probably to create a local scope block within your loop so that locationName actually refers to a different variable for every time you add a delegate/anonymous function to do the geocoding. Placing the var in the loop does not create a new instance of the variable, the var declaration essentially gets moved to the top of the enclosing scope block.

for(var i=0; i<myObjList.length; i++){
    var fullAddress = myObjList[i].Address + ", " + myObjList[i].City + ", " + myObjList[i].State + ", " + myObjList[i].Zip;
    //begin scope block
    (function(){
        var locationName = myObjList[i].LocationName;
        var yourObject = myObjList[i];
         //etc.
        geocoder.geocode( ...);
    //end scope block
    })();
}

Edit:

Or if you were using some framework/ that allows you to pass an anonymous function to execute code for each item in an array, you get that kind of scoping issue taken care for you automatically.

Problem

I have an array list of location objects, and I am using some of them to build a full address, and then geocode that. Once I receive the OK status I am then placing a marker on the map. This all works fine. However, now I would also like to place an info window on each marker with another property from my array list, LocationName. Code is here: ``` function placeMarkers(myObjList){ var geocoder = new google.maps.Geocoder(); for(var i=0; i<myObjList.length; i++){ var fullAddress = myObjList[i].Address + ", " + myObjList[i].City + ", " + myObjList[i].State + ", " + myObjList[i].Zip; /* The variable I would like to have access to in the geocode call */ var locationName = myObjList[i].LocationName; geocoder.geocode( { 'address': fullAddress}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { alert(locationName); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, clickable: true }); markers.push(marker); } else { alert("Geocode was not successful for the following reason: " + status); } }); } } ``` The alert is to just see what locationName is when I get that status OK. But in testing it is just always the same value. Once I can tailor this to reflect the right value each time, then I have code lined up to place the info windows on the marker. Any help would be greatly appreciated!

Original source