设置后如何删除谷歌地图api标记
Posted
技术标签:
【中文标题】设置后如何删除谷歌地图api标记【英文标题】:how remove google map api marker after set 【发布时间】:2017-09-13 19:53:39 【问题描述】:使用我的代码,每次点击地图时都会出现几个标记。
我只想要一个标记,每次点击删除前一个标记并将新标记的纬度/经度设置为新位置。
这是我的代码:
var map;
var markers = [];
function initMap()
var aa = lat: 32.3896651, lng: 48.3791718;
map = new google.maps.Map(document.getElementById('map'),
zoom: 12,
center: aa
);
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event)
addMarker(event.latLng);
document.getElementById("la").value = event.latLng.lat();
document.getElementById("lo").value = event.latLng.lng();
);
// Adds a marker to the map and push to the array.
function addMarker(location)
var marker = new google.maps.Marker(
position: location,
flat: false,
map: map,
draggable: true
);
markers.push(marker);
// Sets the map on all markers in the array.
function setMapOnAll(map)
for (var i = 0; i < markers.length; i++)
markers[i].setMap(map);
// Removes the markers from the map, but keeps them in the array.
function clearMarkers()
setMapOnAll(null);
// Shows any markers currently in the array.
function showMarkers()
setMapOnAll(map);
// Deletes all markers in the array by removing references to them.
function deleteMarkers()
clearMarkers();
markers = [];
【问题讨论】:
看到这个***.com/questions/20101805/… Google Maps API v3: How to remove all markers?的可能重复 【参考方案1】:通过每次添加新标记,您将在页面中创建许多对象。 为什么不重新使用现有的标记?使标记全局而不是标记数组,
var marker = null;
然后使用 setPosition 来更改现有标记对象的位置:
marker.setPosition(location);
这样,您只使用一个标记,只是在不同的位置。
var map;
var marker = null;
function initMap()
var aa = lat: 32.3896651, lng: 48.3791718;
map = new google.maps.Map(document.getElementById('map'),
zoom: 12,
center: aa
);
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event)
addMarker(event.latLng);
document.getElementById("la").value = event.latLng.lat();
document.getElementById("lo").value = event.latLng.lng();
);
// Adds a marker to the map and push to the array.
function addMarker(location)
if(marker)
marker.setPosition(location);
else
marker = new google.maps.Marker(
position: location,
flat: false,
map: map,
draggable: true
);
// Sets the map on all markers in the array.
function setMapOnAll(map)
marker.setMap(map);
// Removes the markers from the map, but keeps them in the array.
function clearMarkers()
marker.setMap(null);
// Shows any markers currently in the array.
function showMarkers()
marker.setMap(map);
// Deletes all markers in the array by removing references to them.
function deleteMarkers()
clearMarkers();
【讨论】:
哦,已经修好了,感谢lottttttttt上帝保佑你【参考方案2】:查看此文档了解更多详情:
https://developers.google.com/maps/documentation/javascript/examples/marker-remove
【讨论】:
当用户点击时,将添加一个新标记,但我希望标记的位置更改为用户点击的位置以上是关于设置后如何删除谷歌地图api标记的主要内容,如果未能解决你的问题,请参考以下文章