最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Google maps API v3, can't get clicked marker - Stack Overflow

programmeradmin5浏览0评论

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('pose');
                    },
                    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.

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('pose');
                    },
                    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.

Share Improve this question edited Mar 7, 2012 at 12:14 SERPRO asked Mar 7, 2012 at 11:57 SERPROSERPRO 10.1k8 gold badges49 silver badges64 bronze badges 2
  • Sounds to me like a closure problem. What does console.log line print? A number same as markers.length? – Salman Arshad Commented Mar 7, 2012 at 11:59
  • I think that too.. but I tried other ways.. and still got the same result. – SERPRO Commented Mar 7, 2012 at 12:01
Add a ment  | 

2 Answers 2

Reset to default 3

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

It´s never too late, so, if I understood correctly, this is the aproach y would take.

When intantiating the markers, add them to an array after their individual setup is pleted.

var MySiteWithMap = { 
    markersArray : [], //Markers array
    map : {}, //Map object instance
    init : function() {

       var mapCanvas = document.getElementById("map");
       var mapOptions = {
         center : new google.maps.LatLng(-26.816667, -65.216667),
         zoom : 11
       };
       this.map = new google.maps.Map(mapCanvas,mapOptions);

       /*
       The following is used to get the Lat and Lng where the user clicks. 
       It may be useful to store the last coordinate where the user clicked.
       */
       this.map.addListener("click", function(event){
          var lat = event.latLng.lat();
          var lng = event.latLng.lng();
          console.log("Lat: "  + lat + "  Lng: "  +  lng);
       });

       MySiteWithMap.initMarkers();

    },
    initMarkers : function(url){
         $.get(url).done(function(result){
            var lat;
            var lng;
            $.each(result,function(index,element){
               lat = element.Latitud;
               lng = element.Longitud;

               var position = new google.maps.LatLng(lat,lng);

               var marker = new google.maps.Marker({
                   position : position,
                   map : _this.map,
                   id : element.id //Supposing it's a primary key from the DB or some other unique id.
               });
               marker.addListener('click',function(){
                   console.log(this.id)
               });

               Mapas.markersArray[marker.id] = marker; 
        })
    }
}

By doing so, you have an array of Marker objects. If you want to get a reference to an specific marker instance, an option would be to get the id of the clicked marker and look for it on the "markersArray".

If you want to get the position (or any other properties) of a marker, you can do something like this:

console.log(MySiteWithMap.markersArray[123].position)

Hope this helps!

发布评论

评论列表(0)

  1. 暂无评论