-1

I am showing multiple markers on a map and am looking to get each infowindow to show the content for each location.

I'm almost there with this code however, I can not get the infowindow to get the value from the array for the current iteration. It works if I stipulate the index of the array.

For example

//Gives the 6th object in the array and shows the correct content
var content= (apartments[6].info);

//Gives Uncaught TypeError: Cannot read property 'info' of undefined
var content= (apartments[i].info);

My Code

var apartments = jQuery.parseJSON(result);
//console.log(array);


var map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: new google.maps.LatLng(53.408371, -2.991573),
    zoom:   5
});         
var geocoder = new google.maps.Geocoder(); 
var infowindow = new google.maps.InfoWindow();     

google.maps.event.addListenerOnce(map, 'tilesloaded', function() {

    for (var i = 0; i < apartments.length; ++i) {

        geocoder.geocode({ address: apartments[i].postcode + ' UK', }, function(result, status) {
            if (status == 'OK' && result.length > 0) {

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

                google.maps.event.addListener(marker, 'click', function() {
                    var content = (apartments[i].info);

                    infowindow.setContent(content);
                    infowindow.open(map, this);
                });                                 
            }
        });
    }   

});
Natty
  • 51
  • 1
  • 3
  • 8
Alex Knopp
  • 907
  • 1
  • 10
  • 30
  • possible duplicate of [Mapping multiple locations with Google Maps JavaScript API v3 and Geocoding API](http://stackoverflow.com/questions/29463131/mapping-multiple-locations-with-google-maps-javascript-api-v3-and-geocoding-api) – geocodezip Jan 06 '17 at 15:56

1 Answers1

1

Common issue with asynchronous functions in loops (the geocoder is asynchronous). By the time the callback function runs, i is past the end of the input array.

You can solve it with function closure:

for (var i = 0; i < apartments.length; ++i) {
  geocodeAddress(apartments[i], infowindow, map);
}

function geocodeAddress(address, infowindow, map) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    address: address.postcode + ' UK',
  }, function(result, status) {
    if (status == 'OK' && result.length > 0) {

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

      google.maps.event.addListener(marker, 'click', function() {
        var content = (address.info);

        infowindow.setContent(content);
        infowindow.open(map, this);
      });
    } else {
      alert("geocoder returns status:" + status)
    }
  });

proof of concept fiddle

geocodezip
  • 158,664
  • 13
  • 220
  • 245