1 问题描述: 为什么无法将marker从map上删除
2 删除代码
clearMarkers() {
this.markers.forEach(marker => {
marker.setMap(null);
});
this.markers = [];
}
3 错误信息
Uncaught TypeError: marker.setMap is not a function
4 尝试的方案
已经给出提示了,问题发生在类型错误,既然marker是google.maps.Marker的实例,
那就检查当前的marker到底是不是和预期相符合。
clearMarkers() {
this.markers.forEach(marker => {
if (marker instanceof google.maps.Marker) {
marker.setMap(null);
}
});
this.markers = [];
}
果然不报错了,那就说明marker并不是google.maps.Marker的实例。此时就要去源头看看
marker的实例化过程。
let marker = new google.maps.Marker({
map: self.map,
position: position,
draggable: true,
animation: google.maps.Animation.DROP,
}).addListener("click", function () {
if (self.getAnimation() !== null) {
self.setAnimation(null);
} else {
self.setAnimation(google.maps.Animation.BOUNCE);
}
});
第一眼,我还没有看出来,感觉没有问题。但是潜意识中意识到,可以将这段链式代码拆解。
let marker = new google.maps.Marker({
map: self.map,
position: position,
draggable: true,
animation: google.maps.Animation.DROP,
});
marker.addListener("click", function () {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
});
代码正常运行。因此问题就出现在这里。
new google.maps.Marker({
map: self.map,
position: position,
draggable: true,
animation: google.maps.Animation.DROP,
}).addListener("click", function () {
if (self.getAnimation() !== null) {
self.setAnimation(null);
} else {
self.setAnimation(google.maps.Animation.BOUNCE);
}
});
返回的不是marker,而是一个事件监听器。