首页 > 解决方案 > 为什么 Leaflet.LayerGroup.Collision 不适用于我的 L.GeoJSON?

问题描述

尝试使用插件"Leaflet.LayerGroup.Collision.js"。我看不到错误是什么,因为它应该在发生碰撞时隐藏文本。所有文本都显示出来,但仍然相互碰撞,在地图上看起来很乱。

下面的示例中可能有什么问题?我试图尽可能地遵循说明,但似乎缺少一些东西!

var point_txt = new L.layerGroup();

function filt_point(feature) {
  if (feature.properties.size === "villages") return true;
}

var collisionLayer = L.LayerGroup.collision({ margin: 8 });

$.getJSON("/data/city_villages.geojson", function(json) {
  var pointLayer = L.geoJSON.collision(null, {
    filter: filt_point,
    pointToLayer: function(feature, latlng) {
      label = String(('<span class="textLabelclassmall">' + feature.properties.Namn + '</span>');
      return new L.marker(latlng, {
        icon: createLabelIcon("textLabelclasssmall", label)
      });
    }
  });

  var createLabelIcon = function(labelClass, labelText) {
    return L.divIcon({
      className: labelClass,
      html: labelText
    });
  };

  pointLayer.addData(json);

  collisionLayer.addLayer(pointLayer);
  collisionLayer.addTo(point_txt);
});

样式.css:

.textLabelclassmall{
left: 1px;
top: -10px;
background-color: transparent;
display: inline-block;
text-align: left;
white-space:nowrap;
letter-spacing: 0.1em;
font-weight: 500;
font-size: 0.5vw;
}

标签: javascripttextleafletcollision-detection

解决方案


的实例Leaflet.LayerGroup.Collision期望添加到自身的层是L.Markers,而不是L.LayerGroup(或派生类的实例,例如L.GeoJSON)的实例 - 它根本没有为该用例做好准备。

在创建单个标记时添加它们,或考虑L.GeoJSON.Collision改用它们。


推荐阅读