32
votes

I am attempting what I imagine to be a fairly common use-case with a leaflet multipolygon object.

I create the MultiPolygon using geojson:

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

What I'd like is to put a simple text label in the center of each polygon. (For example, something like putting state name in the center of each state).

I've looked at: https://groups.google.com/forum/?fromgroups=#!topic/leaflet-js/sA2HnU5W9Fw

Which actually overlays the text, but when I add a bunch of polygons, it appears to put the label off-center in weird ways, and I'm currently unable to track down the problem.

I've also looked at: https://github.com/jacobtoye/Leaflet.label

but that appears to only put the label on polygons when you mouse over the polygon, and does not stay statically on the polygon.

I think my best course of action is to use that first link, and track down why it's changing the location, but in the meantime, if anyone knows of a quick and easy way to lay a label on a polygon in leaflet, I'd be much obliged.

Also, if I have any faulty assumptions about the two links above, please feel free to straighten me out.

Thanks very much in advance.

2
It is pathetic that 6 years and 4 months later there is still not a better way to label polygons in Leaflet. The built in Tooltip Class does NOT provide the same functionality and nearly always require modifications and custom classes to mimic true map labels. Rather than complain I should shut up and write a plugin. In the meantime, I want to add this link into the picture. The Esri Leaflet project describes this method for labels, that also works fine with Leaflet on its own: esri.github.io/esri-leaflet/examples/labeling-features.htmljhickok
I have try using leaflet.label and bindTooltip with custom css for labeling geojson multipolygon in vue js, but this is only this solution that's work on my case. Thanks @jhickokDede kurniawan

2 Answers

22
votes

The leaflet label plugin also allows static labels, see the demo. The only reason the polyline label is not static is that it moves around as you move along the polyline.

You can probably do better than this, by overriding bindLabel() for Polygons but this is a simple way to add a static label to the center of a polygon:

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

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

20
votes

You can use the onEachFeature option of L.geoJson to create a new L.divIcon for each polygon.

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);
  }
);