簡體   English   中英

leaflet (geojson) 多邊形上的簡單 label

[英]Simple label on a leaflet (geojson) polygon

我正在嘗試使用 leaflet 多多邊形 object 進行我想象的相當常見的用例。

我使用geojson創建了MultiPolygon:

var layer = L.GeoJSON(g, style_opts);

我想要的是在每個多邊形的中心放置一個簡單的文本 label 。 (例如,將 state 名稱放在每個狀態的中心)。

我看過: https://groups.google.com/forum/?fromgroups=#!topic/leaflet-js/sA2HnU5W9Fw

它實際上覆蓋了文本,但是當我添加一堆多邊形時,它似乎以奇怪的方式使 label 偏離中心,我目前無法找到問題所在。

我還看過: https://github.com/jacobtoye/Leaflet.label

但是,當您將鼠標懸停在多邊形上時,這似乎只會將 label 放在多邊形上,並且不會靜態停留在多邊形上。

我認為我最好的做法是使用第一個鏈接,並找出它改變位置的原因,但與此同時,如果有人知道在 leaflet 的多邊形上放置 label 的快速簡便的方法,我會非常感激。

另外,如果我對上述兩個鏈接有任何錯誤的假設,請隨時糾正我。

首先十分感謝。

傳單標簽插件還允許使用靜態標簽,請參閱演示 折線標簽不是靜態的唯一原因是它沿着折線移動時會四處移動。

您可以通過覆蓋多邊形的bindLabel()來做得更好,但這是一種向多邊形中心添加靜態標簽的簡單方法:

label = new L.Label()
label.setContent("static label")
label.setLatLng(polygon.getBounds().getCenter())
map.showLabel(label);

http://jsfiddle.net/CrqkR/6/

您可以使用onEachFeature的選項L.geoJson創建一個新的L.divIcon為每個多邊形。

L.geoJson(geoJsonData, {
  onEachFeature: function(feature, layer) {
    var label = L.marker(layer.getBounds().getCenter(), {
      icon: L.divIcon({
        className: 'label',
        html: feature.properties.NAME,
        iconSize: [100, 40]
      })
    }).addTo(map);
  }
);

您可以使用此代碼在多邊形中顯示 label:

  var eu = L.geoJSON(euCountries, {
    
  onEachFeature: function (feature, layer) {
        
   // if (feature.geometry.type === "Polygon") {
            
            var bounds = layer.getBounds();
            // Get center of bounds
            var center = bounds.getCenter();
      //var center = layer.getBounds().getCenter();
            if(feature.properties.name=="russia")
            {
                alert(center)
            }
            layer.bindTooltip(feature.properties.name, {permanent: true, direction: "center", className: "my-labels"});
            layer.on("click", function (e) {
                 layer.bindPopup(feature.properties.name);
            });

     /* var marker =L.circleMarker(center, {color: '', radius:10,Title:20}).bindTooltip(feature.properties.name, {permanent: true, direction: "center", className: "my-labels"});
             map.addLayer(marker);*/
     // var polygonAndItsCenter = L.layerGroup([layer, marker]);
   // }
  },
});
eu.addTo(map);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM