我有一个功能,可以点击一个标记,它为我提供了一个信息框和另一个标记。
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map: map,
icon:props.iconImage
});
if(props.content){
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
marker.addListener('click', function () {
addMarker({
coords:{lat: 59.896874,lng: -5.125914},
iconImage:'pointer12s.png',
content:'<h1>destination</h1>'
});
});
}
}
有没有办法在下次点击时删除这些?
我试着加入了的变体:
.removeEventListener
但我不确定是把它放在同一个函数中还是使用不同的函数?
一个选项是保留对添加的标记的引用。如果尚未添加,则创建标记,如果已存在,则隐藏它(调用setMap(null)
(,然后将其设置为null。移除标记时关闭InfoWindow
。
var addedMarker;
function addMarker(props) {
var marker = new google.maps.Marker({
position: props.coords,
map: map,
icon: props.iconImage
});
if (props.content) {
var infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.infowindow = infoWindow;
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
marker.addListener('click', function() {
if (!addedMarker || !addedMarker.setMap) {
addedMarker = addMarker({
coords: {
lat: 59.896874,
lng: -5.125914
},
// iconImage: 'pointer12s.png',
content: '<h1>destination</h1>'
});
} else {
this.infowindow.close();
addedMarker.setMap(null);
addedMarker = null;
}
});
}
return marker;
}
概念验证小提琴
代码片段:
(function(exports) {
"use strict";
var map;
function initMap() {
var myLatLng = {
lat: 59.896874,
lng: -5.125914
};
map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: myLatLng
});
addMarker({
coords: {
lat: 59.8,
lng: -5.0
},
content: "content"
});
}
var addedMarker;
function addMarker(props) {
var marker = new google.maps.Marker({
position: props.coords,
map: map,
icon: props.iconImage
});
if (props.content) {
var infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.infowindow = infoWindow;
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
marker.addListener('click', function() {
if (!addedMarker || !addedMarker.setMap) {
addedMarker = addMarker({
coords: {
lat: 59.896874,
lng: -5.125914
},
// iconImage: 'pointer12s.png',
content: '<h1>destination</h1>'
});
} else {
this.infowindow.close();
addedMarker.setMap(null);
addedMarker = null;
}
});
}
return marker;
}
exports.initMap = initMap;
})((this.window = this.window || {}));
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Markers</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap&libraries=&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>