Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple label on a leaflet (geojson) polygon

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.

like image 431
Hoopes Avatar asked Nov 09 '12 22:11

Hoopes


People also ask

What is GeoJSON in JavaScript?

GeoJSON is a widely-used data format for displaying vectors in web maps. It is based on JavaScript object notation, a simple and minimalist format for expressing data structures using syntax from JavaScript.


2 Answers

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/

like image 171
flup Avatar answered Sep 28 '22 02:09

flup


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);   } ); 
like image 30
Brendan Nee Avatar answered Sep 28 '22 02:09

Brendan Nee