0

I have a function that I using to gather GPS coordinates from Google, using 10 records from a customer database as an address source.

I am successfully retrieving the data, and populating the arrResult array with GPS coordinates. Using the js console, I have determined that the arrCustName and arrCustFullAddress arrays are populated correctly, but all attempts to reference them using the same index variable (intX) that is being used to populate arrResult fails.

It seems as though my problem is that when I am referencing these arrays using the index intX, I always get 10 as the value of intX.

Any ideas why this might be would be much appreciated.

function CUSTAddr(){  
   for (var intX = 0; intX < arrFullAddress.length; intX++){
      geocoder.geocode( { 'address': arrFullAddress[intX]},  function(results, status) {
   if (status == google.maps.GeocoderStatus.OK) {
        var loc=results[0].geometry.location;
        map.setCenter(loc);
        arrResult[intX]=loc.lng()+","+loc.lat();
        var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
            });
        alert(intX);
        alert(arrFullAddress[intX]);
        alert(arrCustName[intX]);
        alert(arrResult[intX]);
    } else {
    arrResult[intX]="Failed: " + status;
            alert(arrFullAddress[intX]);
            alert(arrCustName[intX]);
            alert(arrResult[intX]);
        }
  });
 }
}
Skye Bowen
  • 49
  • 7
  • 1
    That's because your using an async function, basically all your for loops will be run in parallel.. You could use a closure to capture your intX.. If your using a mordern javascript, you could also change the var to a let, this will do the capture for you. – Keith Aug 31 '17 at 22:17
  • Thank you, I see what you are talking about now. Apparently, I stared at this way too long yesterday. – Skye Bowen Sep 01 '17 at 14:08

0 Answers0