Javascript 传单循环检查簇中是否已存在标记(以免重复)
我有一张单张地图,上面有一个国家人口最多的10个城市的标记。当用户单击城市标记时,会发出AJAX调用。我将城市lat、lng和国家代码传递给API,API返回5个附近机场(名称、lat、lng)。然后,我循环遍历生成的JSON数据,在地图上为每个机场放置标记 我的问题是,一些城市相互靠近,因此有时会在地图上放置一个重复的机场标记 我想防止地图上出现重复标记。我尝试创建一个新的数组,然后对其进行过滤,但我无法使其正常工作 我还想知道这个问题是否有更简单的解决方案。任何帮助都将不胜感激。相关代码如下:Javascript 传单循环检查簇中是否已存在标记(以免重复),javascript,jquery,leaflet,leaflet.markercluster,Javascript,Jquery,Leaflet,Leaflet.markercluster,我有一张单张地图,上面有一个国家人口最多的10个城市的标记。当用户单击城市标记时,会发出AJAX调用。我将城市lat、lng和国家代码传递给API,API返回5个附近机场(名称、lat、lng)。然后,我循环遍历生成的JSON数据,在地图上为每个机场放置标记 我的问题是,一些城市相互靠近,因此有时会在地图上放置一个重复的机场标记 我想防止地图上出现重复标记。我尝试创建一个新的数组,然后对其进行过滤,但我无法使其正常工作 我还想知道这个问题是否有更简单的解决方案。任何帮助都将不胜感激。相关代码如下
if(map.hasLayer(capCityCluster)){
地图移除层(capCityCluster);
}
capCityCluster=新的L.markerClusterGroup();
map.addLayer(capCityCluster);
var largeCityMarker=L.marker(新L.LatLng(城市化,城市化)({
图标:cityIcon
})).bindPopup(`${cityName}${cityInfo}
`,cityOptions)。一次('click',函数(e){
飞行图(e.latlng,10);
$.ajax({
url:“assets/php/airports.php”,
键入:“GET”,
数据类型:“json”,
数据:{
lat:this.getLatLng().lat,
lng:this.getLatLng().lng,
countryCodeA2:borderCountryCode,
},
成功:功能(结果){
//机场标志
result.data.capCityAirports.items.forEach(airport=>{
var airportIcon=L.icon({
iconUrl:'assets/img/icons/airport.png',
iconSize:[50,50],
popupAnchor:[0,-15]
});
airportName=airport.title;
airportLat=airport.position.lat;
airportLng=airport.position.lng;
var airportMarker=L.marker(新的L.LatLng(airportLat,airportLng)({
图标:空中体育
})).bindpoop(airportName);
capCityCluster.addLayer(airportMarker);
});
您可以浏览组中的所有图层,并检查是否存在具有相同latlngs的标记:
var alreadyExists = false;
var latlng = new L.LatLng(airportLat, airportLng);
capCityCluster.getLayers().forEach((layer)=>{
if(!alreadyExists && layer instanceof L.Marker && layer.getLatLng().equals(latlng)){
alreadyExists = true;
}
});
// if alreadyExists is true, it is a duplicate
if(!alreadyExists){
var airportMarker = L.marker(latlng, {
icon: airportIcon
}).bindPopup(airportName);
capCityCluster.addLayer(airportMarker);
}
您在创建标记时也有错误。请删除选项周围的()
:
var airportMarker = L.marker(new L.LatLng(airportLat, airportLng), >>>(<<<{
icon: airportIcon
}>>>)<<<).bindPopup(airportName);
var airportMarker=L.marker(新的L.LatLng(airportLat,airportLng),>>>>()非常感谢!这很有效,但我确实必须将getLatLngs()更改为getLatLng(),而不带“s”。它似乎是这样工作的,但我想知道这是否可能在某个时候导致问题?这是我的错误,一个输入错误!标记层没有getLatLngs()
,getLatLng()
正确