Google地图标记数据

Dar*_*g8r 3 javascript ajax jquery google-maps

我正在对服务器进行ajax调用,以获取要在谷歌地图上显示的纬度/长度列表.我也为每个标记添加了"点击"事件.诀窍是我需要能够将一些额外的数据存储到标记中,以便知道我正在处理的ID(来自数据库),所以我稍后将它与数据库匹配.我正在使用Title属性来显示一些友好信息.AJAX,标记创建和点击事件工作正常.存储标记的额外数据的正确方法是什么?看这里的代码:

$.ajax({
    url: "/location/NearbyHotspots",
    data: {
        lat: marker.position.lat(),
        lng: marker.position.lng(),
        radius: 10
    },
    datatype: "json",
    type: "POST",
    success: function (data, status, xhttp) {
        for (var i = 0; i < data.length; i++) {
            var loc = new google.maps.LatLng(data[i].Lat, data[i].Long);
            var newmarker = new google.maps.Marker({
                position: loc,
                draggable: false,
                map: map,
                title: data[i].Name
            });

            // This doesn't seem to work
            newmarker.hotspotid = data[i].ID;
            google.maps.event.addListener(newmarker, "click", function(mark) {
                alert(mark.hotspotid);
            });
        }
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(textStatus);
    }
});
Run Code Online (Sandbox Code Playgroud)

Dar*_*g8r 11

哈!我想到了."这个"做到了!

google.maps.event.addListener(newmarker, "click", function(mark) {
    alert(this.hotspotid);
});  
Run Code Online (Sandbox Code Playgroud)


nra*_*itz 8

我认为你的方法是正确的,它只是事件处理程序是不正确的.在你的处理程序中

function(mark) {
    alert(mark.hotspotid);
}
Run Code Online (Sandbox Code Playgroud)

mark参数是不是一个标记,如您所愿,但MouseEvent(详见API参考).

为了解决这个问题,您需要使用闭包来传递对标记的引用.这很复杂的循环 - 你不能只使用引用newmarker,因为它只会引用循环中的最后一个标记.有几种不同的方法可以解决这个问题,但最简单的方法是将click事件附加到一个单独的函数中:

success: function (data, status, xhttp) {
    // define a function to attach the click event
    function attachClickEvent(marker) {
        google.maps.event.addListener(marker, "click", function() {
            // the reference to the marker will be saved in the closure
            alert(marker.hotspotid);
        });
    }
    for (var i = 0; i < data.length; i++) {
        var loc = new google.maps.LatLng(data[i].Lat, data[i].Long);
        var newmarker = new google.maps.Marker({
            position: loc,
            draggable: false,
            map: map,
            title: data[i].Name
        });

        newmarker.hotspotid = data[i].ID;
        attachClickEvent(newmarker);
    }
},
Run Code Online (Sandbox Code Playgroud)