Search code examples
javascriptgoogle-maps-api-3markerclusterer

Google maps API v3, can't get clicked marker


I'm getting from my webAPI an array of json objects of users. I can display the marker for each user correctly in their location but I cannot get to work when I click in each of them to get the clicked item, I always get the information from the last in the list.

This is the code I use to put them on the map:

var markers = [];

for ( var i = 0; i < size; i++) {
    var zIndex = membersList[i].type; 
    var latLng = new google.maps.LatLng(membersList[i].latitude,
            membersList[i].longitude);
    var marker = new google.maps.Marker({
        'position' : latLng,
        'shadow' : null,
        'zIndex' : zIndex,
        'title'  : membersList[i].username,
        'id'     : i,
        'icon' : markerImage[membersList[i].type]
    });

    google.maps.event.addListener(marker, 'click', function()
    {
        console.log(marker.id);
        var clicked = membersList[marker.id];
        var mType = ['', 'Couple', 'Male', 'Female'];
        var textType = mType[clicked.type];
        var userName = clicked.username;
        $(this).simpledialog2({
            mode: 'button',
            headerText: "OPTIONS",
            headerClose: true,
            buttonPrompt:  userName+ ' ('+textType+')',
            buttons : {
                'PROFILE': {
                    click: function () {
                        toUser = userName;
                        loadPage('profile');
                    },
                    icon: "info"
                },
                'MESSAGE': {
                    click: function () { 
                        toUser = userName;
                        loadPage('compose');
                    },
                    icon: "star",
                }
            }
        });
    });

    markers.push(marker);
}

markerCluster.addMarkers(markers);

By the way I'm using markerClusterer to display the markers grouped on the map in some zoom levels.


Solution

  • you are using marker which is defined outside of you click function.

    what you need to look at is the google maps api, and find out how to get the clicked marker id

    marker is incrementing through the loop and will ALWAYS be the last marker created