微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决传单循环以检查标记是否已存在于集群中以免复制它

我有一张传单地图,其中包含一个国家人口最多的 10 个城市的标记。当用户单击城市标记时,会进行 AJAX 调用。我将城市 lat、lng 和国家/地区代码传递给返回 5 个附近机场(名称、纬度、lng)的 API。然后我遍历生成的 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);
      });

解决方法

您可以浏览组中的所有图层并检查是否存在具有相同纬度的标记:

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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。