我的想法是使用地图处理点击事件来创建标记。然后处理标记的点击事件以显示该标记的lat()。但是,它总是在Array中显示最终标记的lat()。我无法解决这个错误。请帮我解决这个问题。谢谢所有
function addMarker(location){
var goldStar = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: "yellow",
fillOpacity: 0.8,
scale: 1,
strokeColor: "gold",
strokeWeight: 14
};
mar = new google.maps.Marker({
position: location,
animation: google.maps.Animation.DROP,
icon: goldStar, //or use image
title: "Hello",
map: map
});
makerArray.push(mar);
//console.log(makerArray.length);
//click_Marker(mar);
google.maps.event.addListener(mar, 'click', function(){
alert(mar.getPosition().lat());
});}
function initialize(){
var mapOptions = {
zoom: 12,
overviewMapControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);;
GetCurrentLocation(map);
//Hướng dẫn đi
directionDisplay.setMap(map);
directionDisplay.setPanel(document.getElementById("direction"));
getData();
showListRestaurant();
//Thêm địa điểm vào bản đồ
google.maps.event.addListener(map, 'click', function(event){
addMarker(event.latLng);
});
}
答案 0 :(得分:3)
如果这是您的完整代码,那么您错过了var
变量上的mar
声明。
mar = new google.maps.Marker({
position: location,
animation: google.maps.Animation.DROP,
icon: goldStar, //or use image
title: "Hello",
map: map
});
应该在开头有一个var
var mar = new google.maps.Marker({
position: location,
animation: google.maps.Animation.DROP,
icon: goldStar, //or use image
title: "Hello",
map: map
});
这可以解释您的问题,因为您要添加的每个标记都是对同一对象的引用,因此每次向mar
添加新的单击事件时,您实际上都在更新同一对象的click事件。结果是所有点击事件都具有相同的值。
这是一个有效的jsfiddle: