GMaps JS Geocode: using / passing variables using asynchronous geocoding?

I have a list of arrays of location objects, and I use some of them to create a full address and then geocode. As soon as I get the status OK, I put the marker on the map. All of this works great. However, now I would also like to place an info window on each marker with a different property from the array list, LocationName. The 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); } }); } } 

Warning - just to see what locationName is when I get this status OK. But when testing, this is always the same value. As soon as I can adapt this to reflect the correct value each time, then I have a code built to place information windows on the marker.

Any help would be greatly appreciated!

+4
source share
1 answer

The simplest thing is probably to create a local block of visibility in your loop, so that locationName actually refers to another variable every time you add a delegation / anonymity function for geocoding. Placing var in a loop does not create a new instance of the variable; the var declaration essentially moves to the top of the closing block of the region.

 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 use some kind of framework /, which allows you to pass an anonymous function to execute code for each element in the array, you get a problem that takes care of you automatically.

+4
source

Source: https://habr.com/ru/post/1412031/


All Articles