I have a problem as regarding the assigning of infowindow to each marker in my map.
JS code:
for (i=0;i<location.length;i++){
var id = location[i][0];
var name = location [i][1];
var pos = new google.maps.LatLng(location[i[3],location[i][4]);
var contentString = id;
var infowindow = new google.maps.InfoWindow({content:contentString});
var marker= new google.maps.Marker({position: pos, map: map, title: id});
marker.addListener('click', function() { infowindow.open(map, this);
});
The problem is that my click handler will display the same "id" for each marker (id displayed is the id of my LAST record in my database). Is there a way to display each infowindow for each marker?
Assuming that your location array is fetched and populated from the database...
First of all you have an error:
var pos = new google.maps.LatLng(location[i[3],location[i][4]);
you should fix your brackets and put it this way:
var pos = new google.maps.LatLng(location[ i ][3],location[ i ][4]);
Here is an example:
I tried to follow your example as much as I could since you did not specify an array and made one which corresponds to your array (you can add one more column if your want for your names)
Loop:
for (var i = 0; i < location.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location[i][1], location[i][2]),
map: map,
title: location[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(location[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
Declare your infoWindow before the loop and extract it inside your event
Infowindow:
var infowindow = new google.maps.InfoWindow();
Click event:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(location[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
Full fiddle example: http://jsfiddle.net/eugensunic/7TZFP/5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With