Google displays multiple markers with several unique info fields.

The project I'm working on now requires the implementation of a google map with several markers with several information fields. The map API link seemed like a good starting point:

https://developers.google.com/maps/documentation/javascript/examples/icon-complex

So, I used this code as a base and was built from there. Now the bit that I am stuck adds a unique info box to each marker. here is my source

http://jsfiddle.net/jackthedev/asK5v/1/

as you can see, I am trying to call the first element from which the object in the array has ever been selected, which works fine for lat, long and title, and not for the variable contentstring.

for (var i = 0; i < locations.length; i++) { var office = locations[i]; var myLatLng = new google.maps.LatLng(office[1], office[2]); //works here var infowindow = new google.maps.InfoWindow({content: contentString}); var contentString = '<div id="content">'+ '<div id="siteNotice">'+ '</div>'+ '<h1 id="firstHeading" class="firstHeading">'+ office[0] + '</h1>'+ //doesnt work here '<div id="bodyContent">'+ '</div>'+ '</div>'; var infowindow = new google.maps.InfoWindow({content: contentString}); var marker = new google.maps.Marker({ position: myLatLng, map: map, icon: globalPin, title: office[0], //works here }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(contentString); infowindow.open(map,this); }); } 

To see what I'm trying to explain, simply click on each of the markers in the demo above and you will see an infobox pop-up called "China." for some reason, it captures the first element of the last object for each marker.

What I'm trying to achieve is that all info boxes are unique there, if that makes sense? Therefore, when I click on the marker in Singapore, the info box will pop up with the name of Singapore, using the array objects that I previously defined.

Thanks, and I hope that I was clear enough


+6
source share
1 answer

The problem is that the infoWindow variable becomes rewritable for each iteration of the loop. Usually this will not be a problem, except that the part inside addListener is an asynchronous callback, and by the time each call starts, the link to infoWindow no longer valid.

You can get around this by creating a closure for infoWindow so that each callback function infoWindow its own copy. Use this:

 google.maps.event.addListener(marker, 'click', getInfoCallback(map, contentString)); 

With the included auxiliary function:

 function getInfoCallback(map, content) { var infowindow = new google.maps.InfoWindow({content: content}); return function() { infowindow.setContent(content); infowindow.open(map, this); }; } 

See forked script here.

+8
source

All Articles