每次我的代码调用函数search()时,我希望从上一个搜索调用中放置在地图上的google map标记清除掉地图,并在地图上放置NEW标记。 我需要帮助清除标记。
function search() {
//loading the map with markers
$('.map').addClass('.map-with-searching');
$.ajax({
url: 'https://' + getApiURL(),
data: data,
contentType: 'application/json',
type: 'POST',
success: function (result) {
$('#universitiesList').html('');
for (const row of result.payload) {
locations.push({ lat: row.location.latitude, lng:
row.location.longitude, university: row.campusName, id:row.campusID});
}
//marker.setVisible(false);
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: { lat: locations[i].lat, lng: locations[i].lng },
map: map,
data: {
university: locations[i].university,
id: locations[i].id,
name: locations[i].name,
address: locations[i].address,
image: locations[i].image,
}
});
map.setCenter(new google.maps.LatLng(locations[i].lat, locations[i].lng));
marker.addListener('click', function () {
if (!this.infoWindow) {
this.infoWindow = new google.maps.InfoWindow({
content: '<div class="flex marker-pop-up"><div class="image-container"><img id="building" src="'
+ this.data.image + '"onerror="imgError(this)"; alt="Smiley face" height="110" width="120" /></div></div></div></div>'
});
}
this.infoWindow.open(map, this);
})
};
},
error: function (jqXhr, textStatus, errorThrown) {
//console.log(errorThrown);
}
})
}
答案 0 :(得分:0)
这是一个未经测试的示例-存储对标记的引用,然后调用.setMap(null)将其从地图中删除。
// an array of the markers on the map
let markers = [];
function search() {
// clear the markers
for( const marker of markers ) {
marker.setMap(null);
}
markers = [];
//loading the map with markers
$('.map').addClass('.map-with-searching');
$.ajax({
url: 'https://' + getApiURL(),
data: data,
contentType: 'application/json',
type: 'POST',
success: function (result) {
$('#universitiesList').html('');
for (const row of result.payload) {
locations.push({ lat: row.location.latitude, lng: row.location.longitude, university: row.campusName, id:row.campusID});
}
//marker.setVisible(false);
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: { lat: locations[i].lat, lng: locations[i].lng },
map: map,
data: {
university: locations[i].university,
id: locations[i].id,
name: locations[i].name,
address: locations[i].address,
image: locations[i].image,
}
});
// Store a reference so you can remove markers later
markers.push( marker );
map.setCenter(new google.maps.LatLng(locations[i].lat, locations[i].lng));
marker.addListener('click', function () {
if (!this.infoWindow) {
this.infoWindow = new google.maps.InfoWindow({
content: '<div class="flex marker-pop-up"><div class="image-container"><img id="building" src="' + this.data.image + '"onerror="imgError(this)"; alt="Smiley face" height="110" width="120" /></div></div></div></div>'
});
}
this.infoWindow.open(map, this);
});
};
},
error: function (jqXhr, textStatus, errorThrown) {
//console.log(errorThrown);
}
});
}