3

我正在使用带有 Leaflet.js 的 geoJson 层,在此处显示国家/地区。

我正在添加具有以下内容的国家/地区标签:

L.marker(layer.getBounds().getCenter(), {
     icon: L.divIcon({
         className: 'countryLabel',
         html: feature.properties.name,
         iconSize: [0, 0]
     })
}).addTo(map);

问题是,此应用的标记会阻碍每个国家/地区的鼠标悬停,从而导致鼠标悬停颜色变化和可点击区域出现问题。

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

任何想法都会受到欢迎。

4

1 回答 1

8

我不明白您为什么要通过标记的标记来完成。

您可以将工具提示直接绑定到功能。在你的函数onEachFeaturevar 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'
    }
);

这是另一个小提琴

于 2017-03-21T01:08:13.993 回答