javascript - 如何撤消在 javascript 谷歌地图中创建的标记
问题描述
我使用 JavaScript 制作了谷歌地图。用户左键单击地图的那一刻,它将添加一个图钉,因此我希望当他右键单击该标记时将其删除。
我现在已经做了这个,只添加了标记。
<script>
var map;
function initMap() {
var coords;
var next = document.getElementById('next');
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.7142700, lng: -74.0059700},
zoom: 4
});
var marker;
map.addListener('click', function(event) {
let lat = event.latLng.lat();
let lng = event.latLng.lng();
placeMarker(event.latLng,map);
next.onclick = function() {
var socket = io.connect("http://localhost:3000");
if(socket !== undefined)
{
console.log('Connected to Live Server');
socket.emit('pin-coords',{
lat:lat,
lng:lng
});
socket.on('redirect', function(destination) {
console.log('am ajuns aici');
window.location.href = destination;
})
}
};
});
function placeMarker(location,map) {
if (marker == null)
{
marker = new google.maps.Marker({
position: location,
map: map
});
} else { marker.setPosition(location); } }
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer>
</script>
我真的不知道从哪里开始,我的意思是我正在考虑 map.addListener('click')... 我应该添加另一个侦听器进行删除,因为我有坐标,但找不到东西在文档中。唯一的方法是使用
marker.setMap(null);
,但是我的函数 placeMarker 没有返回标记,也找不到右键单击的键码。如果你能帮助我,我会很高兴和感激。先感谢您!
解决方案
要在右键单击时将标记的 map 属性设置为 null ,请将事件侦听器添加到标记以侦听rightclick
事件。在事件侦听器回调函数中,this
将引用标记 call this.setMap(null);
。
marker.addListener('rightclick', function() {
this.setMap(null);
});
代码片段:
var map;
function initMap() {
var coords;
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 40.7142700,
lng: -74.0059700
},
zoom: 4
});
var marker;
map.addListener('click', function(event) {
let lat = event.latLng.lat();
let lng = event.latLng.lng();
placeMarker(event.latLng, map);
});
function placeMarker(location, map) {
if (marker == null) {
marker = new google.maps.Marker({
position: location,
map: map
});
marker.addListener('rightclick', function() {
this.setMap(null);
})
} else {
marker.setPosition(location);
}
}
}
/* 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;
}
<div id="map"></div>
<p>Click on the map to add markers.</p>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
推荐阅读
- python - 如何在循环中从列表中弹出随机项目
- android - JobScheduler 如何知道作业是否已失败以使其重试?
- powershell - 无法在 PowerShell 中修剪字符串
- sql - 特定类型代码无效和方法调用 impex.exportItemsFlexibleSearch 错误
- node.js - 在此环境中未启用请求的功能
- swift - 由于字典,Swift“无法推断复杂的闭包返回类型;添加显式类型以消除歧义”
- python - Python:用于拟合 HMM 模型的进度条?
- swiftui - 在 SwiftUI 中对形状进行分组
- java - Hive 太慢了,如何对小文件进行分组?
- java - 如何实现 AuthInvalidCredentialsException?