Leaflet.js geoJson 标签

3
我是使用Leaflet.js的geoJson图层,在这里展示国家链接。我正在使用以下代码添加国家标签:
L.marker(layer.getBounds().getCenter(), {
     icon: L.divIcon({
         className: 'countryLabel',
         html: feature.properties.name,
         iconSize: [0, 0]
     })
}).addTo(map);

问题在于,应用此标记会阻碍每个国家区域内的鼠标悬停,导致鼠标悬停颜色变化和可点击区域出现问题。
在leaflet 1.0.3中,是否有更好的解决方案来提供不会阻碍国家可点击区域的标签?
我尝试过使用Leaflet.Label扩展的代码,如下所示:
var label = new L.Label();
label.setContent(feature.properties.name);
label.setLatLng(center);
map.showLabel(label);

或者

L.marker(center)
  .bindLabel('test', { noHide: true })
  .addTo(map);

但是这些会导致错误;我理解在v1之后,这个插件的功能已经被整合到Leaflet.js中。

这确实有效,但我更喜欢直接的标签而不是工具提示:

var marker = new L.marker(center, { opacity: 0.00 }); //opacity may be set to zero
marker.bindTooltip(feature.properties.name, { permanent: true, className: "my-label", offset: [0, 0] });
marker.addTo(map);

欢迎提出任何想法。

1个回答

9
我不明白为什么你想要用标记来完成它。
您可以直接将工具提示绑定到功能上。在您的函数onEachFeature中,您可以这样做,而不是使用var label...
layer.bindTooltip(
    feature.properties.name,
    {
        permanent:true,
        direction:'center',
        className: 'countryLabel'
    }
);

使用这个CSS:
.countryLabel{
  background: rgba(255, 255, 255, 0);
  border:0;
  border-radius:0px;
  box-shadow: 0 0px 0px;
}

这里是代码演示编辑 好的,我明白了,您想使用标记来手动设置位置。以下是一个可行的解决方案:
您可以定义一个哈希表,其中包含所有例外国家的latLng,即那些特征中心不是您想要的中心的国家。
var exceptions = {
    'France': [45.87471, 2.65],
    'Spain': [40.39676, -4.04397]
}

为了显示标签,您需要在正确的位置放置一个不可见的标记,并绑定一个工具提示。
var label = L.marker(
    exceptions[feature.properties.name] || layer.getBounds().getCenter(),
    {
        icon: L.divIcon({
            html: '',
            iconSize: [0, 0]
        })
    }
).addTo(map);

label.bindTooltip(
    feature.properties.name,
    {
        permanent:true,
        direction:'center',
        className: 'countryLabel'
    }
);

这里是另一个代码片段


不幸的是,我需要指定标签放置的位置,因为特征的中心并不总是指向我想要的位置,例如法国有其他领土,因此标签会出现在海洋中。我能指定它的位置吗? - Alex
谢谢,我想我也可以使用偏移量:[0, 0]选项并将其传递给geoJson数据。感谢您的帮助。 - Alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接