Simple label on a leaflet (geojson) polygon

Hoopes picture Hoopes · Nov 9, 2012 · Viewed 45.5k times · Source

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.

Answer

flup picture flup · Jan 13, 2013

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/