【发布时间】:2016-04-08 10:24:47
【问题描述】:
我正在尝试使用 google maps javascript api 创建以下内容:页面加载后,应在用户位置设置标记,现在可以使用。之后,应该在用户点击地图的地方添加一个标记,并删除前一个标记。一个标记应该只在地图上。现在以前的标记不会被删除,而其他标记不会被添加我不想要的。我该怎么做才能在地图上始终拥有一个标记?
var markers = [];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 7
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
deleteMarkers();
addMarkers(event.latLng);
});
addMarkers(pos);
// Adds a marker to the map and push to the array.
function addMarkers(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
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);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
marker = [];
}
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
【问题讨论】:
-
我在发布代码
Uncaught ReferenceError: markers is not defined时收到一个javascript错误@ -
当我修复它并将原始标记推到数组上时,它对我有用。
-
哦,对不起,我没有注意到你的 cmets。你会这么好,并发布工作代码作为答案吗?
-
使用我的实际代码,我得到“未捕获的类型错误:marker.push 不是函数”
-
我自己搞定了,但感谢您的帮助:)
标签: javascript google-maps google-maps-api-3 marker