[GIS] How Do I Add Custom “Region” labels with GeoJSON polygon style datapoints, similar to country names

geojsonlabelingleafletpolygon

I have a Simple CRS map I've set up in Leaflet, and I'd like to label portions of the map with just text labels, similarly to how on a typical World Map you'd see all the continents, then zooming in it shows countries, then states, essentially having text labels only for certain zoom levels.

Is there a way to create these labels and automatically center them with GeoJSON coordinates for polygons around the regions I would like to label?

Best Answer

Anyone who sees this in the future, with Leaflet 1.0.0 and higher, you can simply bind the tooltip to the polygon itself, and the "center" direction will actually center it much better than trying to center on a marker would.

My final code looked like this:

sceneLayer.eachLayer(function(layer) {
  var fontSize = layer.feature.properties.area / map.getZoom() * 30000;
  if(fontSize > 1) {
    layer.bindTooltip("<span style='font-size: " + fontSize + "px'>" + layer.feature.properties.name + "</span>", {
      className: "label",
      permanent: true,
      direction: "center"
    }).openTooltip();
   }
});

The fontSize calculation will vary from person to person, and if you simply want a fixed size, that works too, but this automatically attempts to adjust the font size based on zoom level.