Google Maps: Event Listener only remembering final value of variable

I'm putting together a Google Map which contains the locations of various test centres around my country. It plots a marker on each county, and when you click the county marker, it zooms in and gives an overview of the test centres in that county. I'm also using jQuery with this.

Here's the problem:

When I plot the county markers and click on them, it always zooms to the last county. The code I'm using to plot the counties is as follows:

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;
        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

        // Add the marker to the map

I'm using basically the exact same method to pass HTML into an event listener for when you click the county level markers, and that works fine. For some reason key is always the value of the final county. I've tried passing in key as a variable to the function, but it just becomes equal to the longitude and latitude of the current map poisition.

Maybe I'm doing something idiotic? It wouldn't be the first time :) Any help would be much appreciated.



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

GEvent.addListener(marker, "click",
    (function(key) {
        return function() {
            // Zoom to county


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.