39

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.

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Hoopes
  • 3,943
  • 4
  • 44
  • 60
  • 7
    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: https://esri.github.io/esri-leaflet/examples/labeling-features.html – jhickok Mar 18 '19 at 15:24
  • 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 @jhickok – Dede kurniawan Apr 19 '21 at 01:54

3 Answers3

23

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/

flup
  • 26,937
  • 7
  • 52
  • 74
  • 1
    Thanks for the answer. Managed to get that to work. You do need to add the label to the map before calling `showLabel()` though: `label.addTo(map)` – Ben Aug 06 '13 at 12:59
  • I must have been doing something wrong then... thanks for the update – Ben Aug 07 '13 at 11:37
  • 1
    as of leaflet 1.0 the label plugin has been replaced by the new core feature for tooltips: http://leafletjs.com/reference-1.0.0.html#tooltip – Christian Fritz Dec 06 '16 at 00:46
22

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);
  }
);
Brendan Nee
  • 5,087
  • 2
  • 33
  • 32
  • 2
    How would you make this work if you toggle the 'geoJsonData' as a feature layer on the map? Your current method adds the labels to the map at start. Thanks for any tips. – redshift Nov 20 '15 at 16:50
  • if your `L.geoJson` layer is saved in a variable called `geojson` you can call `geojson.clearLayers()` and then `geojson.addData(newGeoJsonData)` – clhenrick Mar 21 '16 at 17:27
  • @redshift .. check my answer here http://stackoverflow.com/questions/31691297/how-to-remove-a-leaflet-label-when-a-topojson-layer-containing-it-is-removed/31695242#31695242 – muzaffar May 04 '16 at 07:59
  • Edit queue is full. The code is missing a } before the last ) – jgm_GIS Sep 28 '22 at 20:28
0

you can use this code to show label in polygon :

  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);
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 17 '22 at 14:28