我有一张地图,它根据搜索填充标记。我正在尝试使用较新的谷歌地图功能AdvancedMarkerView
所以我可以用自定义 HTML 填充它 - 但是,随着我的搜索更新,我想刷新旧标记并在需要时放置新标记......但我一生都无法弄清楚如何做?https://developers.google.com/maps/documentation/javascript/reference/advanced-markers https://developers.google.com/maps/documentation/javascript/reference/advanced-markers
下面放置自定义标记。有用。
const content = document.createElement('div');
content.className = 'marker-title';
content.textContent = item.title;
const marker = new google.maps.marker.AdvancedMarkerView({
map,
position: item.position,
content
});
通常对于标记,就像在旧标记中一样,我使用以下代码删除了它们,markers.forEach((marker) => marker.setMap(null))
但这似乎不适用于高级标记。由于创建高级标记时返回的标记指向该元素,我也尝试做marker.remove()
认为 HTML 元素将成为目标,但没有雪茄。
当涉及到高级标记时,我无法在 Google API 文档中找到任何具体示例,对于其他提出相同问题的人来说也是如此。
没有setMap()
或其他方法来调用AdvancedMarkerView class https://developers.google.com/maps/documentation/javascript/reference/advanced-markers切换其可见性或将其从地图中删除。
虽然不是很清楚,但是文档 https://developers.google.com/maps/documentation/javascript/advanced-markers/add-marker says:
要从地图上删除标记,请设置markerView.map
财产给null
.
下面的工作示例:
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 37.39094933041195, lng: -122.02503913145092 },
zoom: 14,
mapId: "4504f8b37365c3d0",
});
const draggableMarker = new google.maps.marker.AdvancedMarkerView({
map,
position: { lat: 37.39094933041195, lng: -122.02503913145092 },
draggable: true,
title: "This marker is draggable. Click to remove.",
});
draggableMarker.addListener("click", (event) => {
// Remove AdvancedMarkerView from Map
draggableMarker.map = null;
});
map.addListener("click", (event) => {
// Set AdvancedMarkerView position and add to Map
draggableMarker.position = event.latLng;
draggableMarker.map = map;
});
}
window.initMap = initMap;
#map {
height: 160px;
}
p {
font-family: Arial;
font-size: 0.75em;
margin: 2px 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Draggable Advanced Marker</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<p>Click marker to remove it from map. Click on map to reposition / add marker.</p>
<div id="map"></div>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=marker&v=beta"
defer
></script>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)