3

I'm having a hard time getting the information in the infowindow on a Google Map Marker correct. The markers are in the correct place but, this is passing the name of the second place into both the first and second infowindows.

<script>
 function initMap() {
      var mapOptions = {
              zoom: 14,
              scrollwheel: false,
              center: new google.maps.LatLng(31.44, -100.47)
            }

      var map = new google.maps.Map(document.getElementById('super_map'), mapOptions);

      var geocoder = new google.maps.Geocoder();

      var addresses = ["3000 Main St San Angelo TX", "4001 Sunset Dr San Angelo TX"];

      var names = ['First Place', 'Second Place'];

     for(var x = 0; x < addresses.length; x++){
        var name = names[x];

        geocoder.geocode( { 'address': addresses[x]}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {


            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                animation: google.maps.Animation.DROP,
            });

            var contentString = name;

            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });

            google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map,marker);
            });
          }

        });
     }

    }

    google.maps.event.addDomListener(window, 'load', initMap);
    google.maps.event.addDomListener(window, 'resize', initMap);
</script>

I've tried to set it with the setContent but with the same results...

 google.maps.event.addListener(marker, 'click', function() {
              infowindow.setContent(names[0]);      
              infowindow.open(map,marker);
            });
3
  • 2
    geocoder.geocode is asynchronous, by the time the callback is called, which is after your for loop has finished, name will be the last names[x] - Sep 1, 2016 at 22:41
  • Possible duplicate of Calling an asynchronous function within a for loop in JavaScript Sep 1, 2016 at 22:41
  • Thank you for the information. I'll see if I can apply it to my situation the lessons in your link you provided.
    – Miles
    Sep 1, 2016 at 22:51

2 Answers 2

3

One option to solve your issue would be function closure on the "name". The code below creates an anonymous function for each iteration of the loop which holds function closure on the name variable.

geocoder.geocode({
  'address': addresses[x]
// get function closure on "name"
}, (function(name) {
  return function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        animation: google.maps.Animation.DROP,
      });
      var contentString = name;
      var infowindow = new google.maps.InfoWindow({
        content: contentString
      });
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
      });
    }
  }
})(name));

proof of concept fiddle

code snippet:

function initMap() {
  var mapOptions = {
    zoom: 14,
    scrollwheel: false,
    center: new google.maps.LatLng(31.44, -100.47)
  }
  var map = new google.maps.Map(document.getElementById('super_map'), mapOptions);
  var bounds = new google.maps.LatLngBounds();
  var geocoder = new google.maps.Geocoder();
  for (var x = 0; x < addresses.length; x++) {
    var name = names[x];
    geocoder.geocode({
      'address': addresses[x]
    }, (function(name) {
      // get function closure on "name"
      return function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          bounds.extend(results[0].geometry.location);
          map.fitBounds(bounds);
          var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
            animation: google.maps.Animation.DROP,
          });
          var contentString = name;
          var infowindow = new google.maps.InfoWindow({
            content: contentString
          });
          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
          });
        }
      }
    })(name));
  }
}

google.maps.event.addDomListener(window, 'load', initMap);
google.maps.event.addDomListener(window, 'resize', initMap);
var addresses = ["3000 Main St San Angelo TX", "4001 Sunset Dr San Angelo TX"];
var names = ['First Place', 'Second Place'];
html,
body,
#super_map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="super_map"></div>

0
3

Hi as explained in the comments above that geocoder call wont work in the loop.

However once you clean that up you can pass data to the marker by setting the data proper on the marker:

 var marker = new google.maps.Marker({
            map: map,
            data: someDataProperty,// either the geocoder result or custom data
            position: results[0].geometry.location,
            animation: google.maps.Animation.DROP,
        });

then in your click even they get the marker and use the data property:

google.maps.event.addListener(marker, 'click', function() 
 {
          infowindow.setContent(marker.data.name;      
          infowindow.open(map,marker);
        });

Here is a JS fiddle showing how this works: https://jsfiddle.net/loanburger/dh4whm25/

2
  • 2
    Passing customize data to the data property will not solve OP's issue. His problem was because of geocoder.geocode(..) been an async function and the callback closure fn he had for it would always be referencing the last element of the Name array. As pointed by @JaromandaX 's link, OP's problem can potentially be solved by 1 of the many methods, e.g. using an immediate invoked function, using the .forEach() or he can also synchronously invoke the async fn (which is inefficient).
    – Samuel Toh
    Sep 2, 2016 at 1:45
  • Hi - Yes I understand but given the "Question in the topic this demonstrated how to pass data. I did achknowledge the issue with doing an async call in the loop, and agree seperate functions would solve this.
    – TResponse
    Sep 2, 2016 at 3:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.