[GIS] Leaflet JS – Add text to circles

javascriptleaflet

I am trying to create a map using Leaflet with circles that indicate distances on the map at current zoom level (map scale). See illustration below:

Circles for map scale

I know how to calculate sizes and update the circles themselves, but I am struggling to add the text to the circles.

I have tried the leaflet.label plugin but this wasn't an option because it doesn't support static labels for Vectors.

The alternative seems to be to use a divIcon, but this seems to be a very clunky way to solve my problem, as I will have to edit the options of the divIcon, inside a marker on each zoom event.

What would you advise?

Best Answer

If you do not like the divIcon workaround, be noted that you can also directly add a Leaflet.label to the map, without having it bound to a marker / vector first, even though this is not its initial purpose.

This is similar to adding pop-ups directly to the map. But since this was not expected, you have to manually set the content, position and adding to map:

L.marker([48.86, 2.35]).addTo(map); // The center.

var circle = L.circle([48.86, 2.35], 1000, {
  fill: false
}).addTo(map); // Your circle.

map.addLayer(new L.Label({ // label.addTo(map) is not implemented.
  noHide: true, // Force label to be shown permanently.
  offset: [6, -15] // Counter-act label CSS styling.
}).setContent("500m").setLatLng([
  48.86,
  2.35 + circle._getLngRadius()
]));

Demo: http://jsfiddle.net/ve2huzxw/166/