2

I am using the Google Maps JS API to Geocode some addresses, but I need to have access to a number of variables inside the callback of the geocode function. The geocoder is an asynchronous function.

My code is as follows:

for (var prop in markerData) {
    geocoder.geocode( { address: addressData }, function(results, status) {
        if (status == 'OK') {
            lat = results[0].geometry.location.lat();
            lng = results[0].geometry.location.lng();

            console.log(addressData);

            markerInfo = { 
                lat: lat, 
                lng: lng,
                firstname: markerData[prop].firstname,
                lastname: markerData[prop].lastname,
                company: markerData[prop].company,
                addressFormatted: addressData,
                street: markerData[prop].street,
                city: markerData[prop].city,
                postcode: markerData[prop].postcode,
                telephone: markerData[prop].telephone
            }

            markers[i] = new google.maps.Marker({
                map: map,
                position: {lat: lat, lng: lng},
                title: markerData[prop].firstname + ' ' + markerData[prop].lastname,
                markerInfo: markerInfo
            });

            markers[i].addListener('click', function() {
                updateInfo(this.markerInfo);
            });

            $.get('cache.php', {
                address: addressData,
                lat: lat,
                lng: lng
            });
        }
    });
}

addressData is always the value of the last entry of markerData. markerData data is definitely correct.

I need a way of passing both addressData and markerData to the geocoder.geocode function that will be accessible inside the callback.

Mike
  • 8,767
  • 8
  • 49
  • 103
  • You may want to surround the call with an IIFE. That way the variable passed will remain the same inside. – Arg0n Dec 09 '15 at 15:10
  • I'm unsure why this has been marked as a duplicate, especially with the linked question. It's a different issue found under different circumstances. Just because a problem has the same answer doesn't make it a duplicate question. – Mike Dec 10 '15 at 10:20

1 Answers1

2

Example for my comment:

for (var prop in markerData) {
    (function(addressData){
        geocoder.geocode( { address: addressData }, function(results, status) {
            //Other code
        });
    })(addressData);
}
Arg0n
  • 8,283
  • 2
  • 21
  • 38