Reputation: 10447
I have the old infowindows in a loop problem where the content for the last loop is showing in all infowindows. Yes I know there are several questions about this already on Stack Overflow but none of them seem to work for me.
This is my JavaScript:
var map;
var geocoder;
$(function () {
var mapOptions = {
zoom: startZoom,
center: new google.maps.LatLng(startLat, startLng)
}
var marker, i;
$('#map-canvas').height($('#map-canvas').width() / 2);
var mapOptions = {
zoom: startZoom,
center: new google.maps.LatLng(startLat, startLng)
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if ( ! isAddress && $('#country').val() > 0) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': $('#country').find('option:selected').text()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
}
});
}
for (i = 0; i < distributors.length; i++) {
var $distributor = distributors[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng($distributor.latitude, $distributor.longitude),
map: map
});
var infowindow = new google.maps.InfoWindow();
var html = '<div class="container-fluid" style="width: 300px">\
<h1 class="row-fluid">\
'+($distributor.logo ? '<div class="span3"><img src="'+$distributor.logo+'" style="width: 100%"></div>' : '')+'\
<span class="span9">'+$distributor.name+'</span>\
</h1>\
<div class="row-fluid">\
<div class="span6">'+$distributor.address+'<br>'+$distributor.postcode+'</div>\
<div class="span6">'+($distributor.url ? '<a href="'+$distributor.url+'">'+$distributor.url+'</a>' : '')+'<br>'+$distributor.contactNumber+'</div>\
</div>\
</div>';
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(html);
infowindow.open(map, marker);
}
})(marker, i));
}
})
So far I've tried this answer, but the variables mentioned don't match what I have and I couldn't make them match up, it just didn't work.
I've also tried this answer, but instead of getting different content it removed all but one of my markers.
What am I doing wrong? Can someone please help me sort this out?
Upvotes: 0
Views: 1390
Reputation: 149
Try this after creating infoWindow and html objects:
marker.html = html;
Then build your event listener like this:
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.html);
infoWindow.open(map, this);
});
Upvotes: 7