4
votes

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);
});
1
I think you forgot to define onEachFeature callback in L.geoJson options. See leafletjs.com/reference.html#geojson - YaFred

1 Answers

5
votes

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.net/FranceImage/ro54bqbz/ using Leaflet.label