0

I have the following code which receives the list of addresses from php script, then sends them for geocoding to google maps and then creates markers and info windows.

My goal is to have the original addresses received from php script displayed on the info windows.

But while the markers are created correctly, the address on all info windows turns out to be the same - the value of the last variable in 'for' loop.

My question is: how can I pass correctly the addresses to the callback function?

$.getJSON('dmvsearch.php?zipcode='+zipcode, null, function (res) {
  for (var x = 0; x < res.length; x++) {
        var address=res[x];
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map
            });
            var infowindow = new google.maps.InfoWindow();
            infowindow.setContent('<div><strong>' + address + '</strong><br>');
            marker.addListener('click', function() {
              infowindow.open(map, marker);
            });


        });
    }
});
  • Don't use `for` loops in asynchronous situations. Try the same code with `res.forEach` and it will start to work. – Tomalak Sep 02 '16 at 09:46
  • Unrelated to the issue at hand, but don't build your URLs like that. jQuery makes it very easy to pass parameter objects. Use that. `$.getJSON('dmvsearch.php', {zipcode: zipcode})`. – Tomalak Sep 02 '16 at 09:52

0 Answers0