gpt4 book ai didi

javascript - 删除谷歌地图中以前的标记并加载新地点

转载 作者:行者123 更新时间:2023-12-02 15:32:46 25 4
gpt4 key购买 nike

我使用 ajax 从外部 json 加载我的地​​点,如下所示:

[{
"id":"1",
"title": "Stockholm",
"lat": 59.3,
"lng": 18.1,
},
{
"id":"2",
"title": "Oslo",
"lat": 59.9,
"lng": 10.8,
},
{
"id":"2",
"title": "Copenhagen",
"lat": 55.7,
"lng": 12.6,
}]

我的 map 在页面中加载,代码如下:

var MapInitialized = false,
$map = $('#googleMap .map');

var mapProp = {
center:new google.maps.LatLng(35.6891970, 51.3889740),
zoom:12,
disableDefaultUI: true,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
animation: google.maps.Animation.DROP,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'bestfromgoogle']
}
};
var map = new google.maps.Map($map[0], mapProp);

var infoWindow = new google.maps.InfoWindow();

$("select").change(function(){

$.ajax({
type: "GET",
url: "places.json",
dataType: "json",
beforeSend: function(){ $(".mapLoading").fadeIn();},
complete: function(){ $(".mapLoading").fadeOut();},
success: function(response){

var LatLngList = new Array();
var marker;

$.each(response, function(key, data) {

Point = new google.maps.LatLng(data.lat, data.lng);

LatLngList.push(Point);

console.log(LatLngList);

marker = new google.maps.Marker({
position: Point,
map: map,
title: data.title
});
});

var bounds = new google.maps.LatLngBounds ();
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
bounds.extend (LatLngList[i]);
}

map.fitBounds (bounds);

}
});
});

我的 HTML 页面上有一个选择器,当用户更改它时,ajax 向 json 发送请求,标记将显示在 map 上。现在我需要删除所有以前的标记并在 map 上加载新标记,而不加载新 map 。

最佳答案

您需要将标记实例保存到一个数组中,以便稍后可以访问它们。

诀窍是使用marker.setMap(null);从 map 上删除标记

var markers = [];

// ...
// success callaback
markers.forEach(function(m) { m.setMap(null); });

markers = response.map(function(data) {
return new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.title
});
});

关于javascript - 删除谷歌地图中以前的标记并加载新地点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33197125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com