2

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?

0

2 Answers 2

1

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.

0
.leaflet-container{
    background: #57677A;
    font-family: 'DM Sans', sans-serif;
    .leaflet-tooltip {
      position: absolute;
      padding: 0;
      background-color: transparent;
      border: none;
      border-radius: 0;
      white-space: pre-wrap;
      box-shadow: none;
  }
  } ///manipulate css to show country labels on geojson map

const onEachCountry = (country, layer) => {
    const countryName = country.properties.name;
    layer.defaultOptions.leaflet.map.on({
      zoomstart:(event)=>{
        layer.unbindTooltip();
        layer.bindTooltip("<span style='font-size: " + event.target._zoom*3 + "px'>" + countryName + "</span>", { className: "ankush", permanent: "true", direction: "center" }).openTooltip();
      }
    });
    layer.bindPopup(countryName);
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.