I have a few google map markers and I am trying to add a click event to each, but for some reason, the text that gets displayed is the same for every marker :(
I think it is a problem with my JS closures (are closures the same thing as scope in JS?)
The map with markers where the problem is happening is here: http://www.comehike.com/outdoors/parks/trailhead.php
What am I doin开发者_Go百科g wrong in the code that I have which makes the same popup window appear for every marker?
Thanks, Alex
You're right, this is a problem with scope and closures. You are defining infoWindow in the global scope and then using it inside of your onclick handler. This means you will always open the infoWindow you created in the last iteration of your for loop.
Change this code:
infoWindow = new google.maps.InfoWindow({
content: contentString
});
to this:
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
Here is a JSFiddle Demo:
I created a dummy array with information attached named markers. We then create a global variable infowindow to hold one instance of your info window. This info window is going to pop up next to the marker that is clicked.
var map;
var global_markers = [];
var markers = [[37.09024, -95.712891, 'trialhead0'], [-14.235004, -51.92528, 'trialhead1'], [-38.416097, -63.616672, 'trialhead2']];
var infowindow = new google.maps.InfoWindow({});
within your markers populating for loop. Basically, instead of holding an instance of infowindow with each marker i attach the content with it, and with the onclick event when a marker is clicked i set the content of the infowindow with the content we saved and then open the infowindow next to the clicked marker:
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
you need to add this
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
otherwise it will keep saying google not found.
精彩评论