Simple label on a leaflet (geojson) polygon

2019-02-01 22:37发布

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.

2条回答
干净又极端
2楼-- · 2019-02-01 23:05

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);
  }
);
查看更多
祖国的老花朵
3楼-- · 2019-02-01 23:09

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/

查看更多
登录 后发表回答