我在地图上有几个标记(在一个数组中),每个标记都有一个自定义ID标记,我给了它们。从侦听器 - 谷歌地图访问标记javascript API3.0
我想要什么: 当我点击一个标记,我想将它的ID添加到另一个数组。
问题: 来自Google的鼠标事件没有目标属性,只有位置,所以我似乎无法直接访问该ID。
我并不是真的不得不求助于使用这个位置来找到最接近它的标记并以这种方式返回它的ID,这是相当复杂的。
所有帮助表示赞赏
我在地图上有几个标记(在一个数组中),每个标记都有一个自定义ID标记,我给了它们。从侦听器 - 谷歌地图访问标记javascript API3.0
我想要什么: 当我点击一个标记,我想将它的ID添加到另一个数组。
问题: 来自Google的鼠标事件没有目标属性,只有位置,所以我似乎无法直接访问该ID。
我并不是真的不得不求助于使用这个位置来找到最接近它的标记并以这种方式返回它的ID,这是相当复杂的。
所有帮助表示赞赏
这是很容易,这要归功于JavaScript和许多其他语言的特征叫做闭包。
只需将创建标记的代码放置在函数内部并设置其事件侦听器,然后使用该特定标记所需的数据为每个标记调用该函数。例如:
var places = [
{
id: 'one', lat: 1, lng: -1, name: 'First'
},
{
id: 'two', lat: 2, lng: -2, name: 'Second'
}
];
for(var i = 0; i < places.length; i++) {
addPlace(places[i]);
}
function addPlace(place) {
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(place.lat, place.lng),
title: place.name
});
google.maps.event.addListener('click', function() {
alert('Clicked ' + place.id + ': ' + place.name);
});
}
我没有测试这个Maps API代码,但代码的细节并不重要。重要的是要明白在代码中使用的place
变量。这是关键部分:该变量可在事件侦听器内部访问,这是因为事件侦听器嵌套在addPlace()
函数中,该函数将place
作为参数。
注意,代码和代码这样的,之间的区别这将不工作:
for(var i = 0; i < places.length; i++) {
var place = places[i];
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(place.lat, place.lng),
title: place.name
});
google.maps.event.addListener('click', function() {
alert('Clicked ' + place.id + ': ' + place.name);
});
}
两者之间的唯一区别是,工作版本提出的循环体在一个单独的函数,它是从循环中调用,而不是将所有代码直接放在循环中。在每次调用的函数中拥有该代码就是创建闭包的内容,这就是让内部事件侦听器能够“看见”外部函数中的变量的功能。
闭包的好处是你可以在的任何类似的情况下使用它们。它不是特定于Maps API或API使用的对象。您甚至可能已经使用了他们已经不认识它,例如在setTimeout()
调用是这样的:
// Display an alert 'time' milliseconds after this function is called
function slowAlert(message, time) {
setTimeout(function() {
alert(message);
}, time);
}
slowAlert('Howdy!', 1000); // Wait a second and then say Howdy!
凡alert()
呼叫在setTimeout()
回调函数里面做而成,它使用的slowAlert()
功能关闭以获取传入该函数的message
变量的值。
这应该有所帮助。我将customId
属性添加到标记对象,然后在标记click
事件中,将id属性分配给新数组。
function initialize() {
var map;
var centerPosition = new google.maps.LatLng(38.713107, -90.42984);
var options = {
zoom: 6,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var bounds = new google.maps.LatLngBounds();
map = new google.maps.Map($('#map')[0], options);
var infoWindow = new google.maps.InfoWindow();
//marker array
var markers = [];
//sencondary array to store markers that were clicked on.
var markerIdArray = [];
for (i = 0; i < 6; i++) {
var lat = 38.713107 + Math.random();
var lng = -90.42984 + Math.random();
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
customId: i //add a custom id to the marker
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', function() {
//add the id to the other array.
markerIdArray.push(this.customId);
//log the content of the array to the console.
console.log(markerIdArray);
});
markers.push(marker);
}
map.fitBounds(bounds);
}
那太好了!非常感谢你,完美工作。 – user1380013 2013-03-27 19:09:24