传单循环检查标记是否已存在于集群中(以免重复它)

leaflet loops to check if marker already exists in cluster (so as not to duplicate it)

我有一张传单地图,其中包含一个国家 10 个人口最多的城市的标记。当用户点击城市标记时,会进行 AJAX 调用。我将城市纬度、经度和国家代码传递给 API,其中 returns 5 个附近的机场(名称、纬度、经度)。然后我循环遍历生成的 JSON 数据以在地图上为每个机场放置标记。

我的问题是有些城市彼此靠近,因此有时会在地图上放置重复的机场标记。

我想防止地图上出现重复的标记。我试过创建一个新数组然后过滤它,但我无法让它工作。

我也想知道是否有更简单的解决方案来解决这个问题。任何帮助将非常感激。相关代码如下:

if (map.hasLayer(capCityCluster)) {
  map.removeLayer(capCityCluster);
}
capCityCluster = new L.markerClusterGroup();
map.addLayer(capCityCluster);

var largeCityMarker = L.marker(new L.LatLng(cityLat, cityLng), ({
  icon: cityIcon
})).bindPopup(`<div class="markerContainer"><h3>${cityName}</h3><img class="markerThumbnail" src='${cityThumbnailImg}' onerror="this.style.display='none'"><p class="markerTxtDescription">${cityInfo}</p><div id="city-link"><a href="//${cityUrl}" target="_blank">${cityText}</a></div></div>`, cityOptions).once('click', function(e) {
  map.flyTo(e.latlng, 10);
  $.ajax({
    url: "assets/php/airports.php",
    type: 'GET',
    dataType: 'json',
    data: {
      lat: this.getLatLng().lat,
      lng: this.getLatLng().lng,
      countryCodeA2: borderCountryCode,
    },
    success: function(result) {
      //airport markers
      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(new L.LatLng(airportLat, airportLng), ({
          icon: airportIcon
        })).bindPopup(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);