您好,并提前致谢。以下修改后的示例Google代码会在鼠标左键单击时创建标记,并将这些标记添加到数组中。那部分工作正常。我试图添加第二个事件处理程序,如果右键单击它,则删除标记。我尝试了很多变化而没有成功。据我所知,使用marker.setMap(null)会将关联的数组元素设置为null,并从显示中删除标记。再次感谢!
<!DOCTYPE html>
<html>
<head>
<title>Marker Test</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas, #map_canvas {
height: 100%;
}
#map-canvas, #map_canvas {
height: 650px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var map;
var markers = [];
function initialize() {
var NY = new google.maps.LatLng(40.739112,-73.785848);
var mapOptions = {
zoom: 16,
center: NY,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
google.maps.event.addListener(map, 'rightclick', function(event) {
marker.setMap(null);
});
}
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
答案 0 :(得分:7)
您希望标记上的'rightclick'事件侦听器,而不是地图。把它放在addMarker函数中:
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
}
注意:这将从地图中删除标记,但不会将其从标记数组中删除。
删除地图上的那个,删除这些行:
google.maps.event.addListener(map, 'rightclick', function(event) {
marker.setMap(null);
});