Google Maps Api v3 - Multiple Info Windows with custom content
I have finally managed to add multiple m开发者_Go百科arkers with custom icons to my Googlemap.
The next step would be to add an individual Infowindow for each marker. Unfortunatelly i cant figure out how.
Here is my script so far:
<script type="text/javascript">
var offender_locations = [
["10010", "http://localhost/safenation/img/map_offender_icon.png"],
["10001", "http://localhost/safenation/img/map_visitor_icon.png"]
];
var myOptions = {zoom: 10,center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("elementid"), myOptions);
var latlng = new google.maps.LatLng(0, 0);
var marker;
var i;
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow();
var geocoder_map = new google.maps.Geocoder();
var address = offender_locations[i][0];
var icon = offender_locations[i][1];
geocoder_map.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: icon
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(offender_locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
} else {alert("The requested offender is not mappable !")};});
}
</script>
I think there now is a problem with the loop. When i try:
var icon = offender_locations[1][1];
all icons are "map_offender_icon.png"
When I use :
var icon = offender_locations[i][1];
nothing changes and all icons are still "map_offender_icon.png"
It seems the var offender_locations[i][1]; is not changing accordingly. The var offender_locations[i][0]; changes accordingly.
Your marker variable is local to your for loop which is not visible outside the loop so the statement
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i)
is not able to set the listener for your marker.
Best way is include your Info window initialization inside your loop to set listeners to your entire markers.
Hope this helps.
The problem has been solved!
Working script:
Javascript Loop - 2nd variable Not Displaying
(Extracted from edit to the original question)
精彩评论