我目前正在对服务器进行ajax调用,以获取要在google地图上显示的经度/纬度列表。我也给每个标记附加了一个"click“事件。诀窍是,我需要能够将一些额外的数据存储到标记中,以便知道我正在处理的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);
}
});发布于 2011-09-13 05:31:38
哈!我想通了。“这”做到了!
google.maps.event.addListener(newmarker, "click", function(mark) {
alert(this.hotspotid);
}); 发布于 2011-09-13 05:25:34
我认为您的方法是正确的,只是事件处理程序不正确。在你的处理程序中
function(mark) {
alert(mark.hotspotid);
}正如您所期望的,mark参数不是一个标记,而是一个MouseEvent (see the API reference for details)。
为了解决这个问题,您需要使用闭包来传递对标记的引用。这在循环中变得很复杂--你不能只引用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);
}
},https://stackoverflow.com/questions/7393988
复制相似问题