Google Maps: An event listener only remembers the final value of a variable

I am collecting a Google map that hosts various testing centers around my country. It displays a marker in each county, and when you click a county marker, it scales and gives an overview of the test centers in that county. I also use jQuery with this.

Here's the problem:

When I draw county markers and click on them, it always scales to the last county. The code I use to build the counties looks like this:

function plotCountyMarkers(county_count) { // Setup a new icon var icon = new GIcon(); var count = 0; // Get the type of icon to display var centre_type = checkCentreType(); if (centre_type == 'dtc') icon.image = dtc_icon; else icon.image = ctc_icon; // Other settings including icon shadow icon.shadow = icon_shadow; icon.iconSize = new GSize(20, 29); icon.shadowSize = new GSize(38, 29); icon.iconAnchor = new GPoint(10, 29); icon.infoWindowAnchor = new GPoint(10, 1); // Get the total number of counties to map var count = county_count.length; for (key in county_count) { // Set the LatLong of the county var countyLocation = new GLatLng(county_locations[key][0],county_locations[key][1]); // Set the title text of the marker var centre_text = county_count[key]==1 ? 'Centre' : 'Centres'; var title = county_locations[key][2]+': '+county_count[key]+' Test '+centre_text; // Add an event listener to the marker var marker = new GMarker(countyLocation,{icon: icon, title: title}); GEvent.addListener(marker, "click", function() { // Zoom to county showCounty(key); }); // Add the marker to the map map.addOverlay(marker); } } 

I use basically the same method to pass HTML to an event listener when you click county level markers, and this works great. For some reason, key always the value of the final district. I tried to switch to key as a variable to a function, but it just becomes equal to the longitude and latitude of the current map binding.

Maybe I'm doing something stupid? This will not be the first time :) Any help would be greatly appreciated.

+2
javascript jquery google-maps event-listener
source share
1 answer

Hi, I changed the event handler to the following and it worked:

 GEvent.addListener(marker, "click", (function(key) { return function() { // Zoom to county showCounty(key); }; })(key) ); 
+4
source share

All Articles