谷歌地图标记在添加新标记时未被清除



我有一个函数,它将地名作为输入,并在谷歌地图上该地方的纬度和液化天然气位置放置一个引脚。它还使用纬度和 LNG 位置设置边界,以将引脚设置为视口。一切正常,但在添加新标记时未清除旧标记。我已经清除了标记数组,但它不起作用。这是我的代码

var place = args.address;
var bounds = new google.maps.LatLngBounds();
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': place.formatted_address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var markers = [];
markers.forEach(function(marker) {
marker.setMap(null);
});
markers.push(new google.maps.Marker({
map: map.map,
icon: icon,
title: place.name,
position: results[0].geometry.location
}));

if (results[0].geometry.viewport) {
bounds.union(results[0].geometry.viewport);
} else {
bounds.extend(results[0].geometry.location);
}
map.map.fitBounds(bounds);
} else {
console.log("error")
}
});

试试这个

var place = args.address;
var bounds = new google.maps.LatLngBounds();
var markers = []; //
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': place.formatted_address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);                 
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = []; // Empty here
markers.push(new google.maps.Marker({
map: map.map,
icon: icon,
title: place.name,
position: results[0].geometry.location
}));

if (results[0].geometry.viewport) {
bounds.union(results[0].geometry.viewport);
} else {
bounds.extend(results[0].geometry.location);
}
map.map.fitBounds(bounds);
} else {
console.log("error")
}
});
javascript google-maps goog

最新更新