最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Polygon labels with Leaflet - Stack Overflow

programmeradmin4浏览0评论

Using leaflet 7.3 and polygon data in GeoJSON, how can I add labels from field: NAME?

Here is example of current GeoJSON polygon data. I would like to enable fixed labels in center of polygon, overlap OK.

var districts = L.geoJson(null, {
  style: function (feature) {
    return {
      color: "green",
      fill: true,
      opacity: 0.8
    };
  },


onEachFeature(feature, layer) {
    layer.on('mouseover', function () {
      this.setStyle({
        'fillColor': '#0000ff'
      });
    });
    layer.on('mouseout', function () {
      this.setStyle({
        'fillColor': '#ff0000'
      });
    });
    layer.on('click', function () {
    window.location = feature.properties.URL;
    });
}

});

$.getJSON("data/districts.geojson", function (data) {
  districts.addData(data);
});

Using leaflet 7.3 and polygon data in GeoJSON, how can I add labels from field: NAME?

Here is example of current GeoJSON polygon data. I would like to enable fixed labels in center of polygon, overlap OK.

var districts = L.geoJson(null, {
  style: function (feature) {
    return {
      color: "green",
      fill: true,
      opacity: 0.8
    };
  },


onEachFeature(feature, layer) {
    layer.on('mouseover', function () {
      this.setStyle({
        'fillColor': '#0000ff'
      });
    });
    layer.on('mouseout', function () {
      this.setStyle({
        'fillColor': '#ff0000'
      });
    });
    layer.on('click', function () {
    window.location = feature.properties.URL;
    });
}

});

$.getJSON("data/districts.geojson", function (data) {
  districts.addData(data);
});
Share Improve this question asked Jan 3, 2015 at 5:28 Bergen88Bergen88 1772 gold badges4 silver badges15 bronze badges 1
  • I think you forgot to define onEachFeature callback in L.geoJson options. See leafletjs./reference.html#geojson – YaFred Commented Jan 3, 2015 at 18:10
Add a ment  | 

1 Answer 1

Reset to default 5

In onEachFeature callback, you can get the center of the L.Polygon created by GeoJSON layer and bind a label to it.

var polygonCenter = layer.getBounds().getCenter();

// e.g. using Leaflet.label plugin
L.marker(polygonCenter)
    .bindLabel(feature.properties['NAME'], { noHide: true })
    .addTo(map);

Here is an example: http://jsfiddle/FranceImage/ro54bqbz/ using Leaflet.label

发布评论

评论列表(0)

  1. 暂无评论