Using leaflet 7.3 and polygon data in GeoJSON, how can I add labels from field: NAME?
Here is example of current GeoJSON polygon data. I would like to enable fixed labels in center of polygon, overlap OK.
var districts = L.geoJson(null, {
style: function (feature) {
return {
color: "green",
fill: true,
opacity: 0.8
};
},
onEachFeature(feature, layer) {
layer.on('mouseover', function () {
this.setStyle({
'fillColor': '#0000ff'
});
});
layer.on('mouseout', function () {
this.setStyle({
'fillColor': '#ff0000'
});
});
layer.on('click', function () {
window.location = feature.properties.URL;
});
}
});
$.getJSON("data/districts.geojson", function (data) {
districts.addData(data);
});
Using leaflet 7.3 and polygon data in GeoJSON, how can I add labels from field: NAME?
Here is example of current GeoJSON polygon data. I would like to enable fixed labels in center of polygon, overlap OK.
var districts = L.geoJson(null, {
style: function (feature) {
return {
color: "green",
fill: true,
opacity: 0.8
};
},
onEachFeature(feature, layer) {
layer.on('mouseover', function () {
this.setStyle({
'fillColor': '#0000ff'
});
});
layer.on('mouseout', function () {
this.setStyle({
'fillColor': '#ff0000'
});
});
layer.on('click', function () {
window.location = feature.properties.URL;
});
}
});
$.getJSON("data/districts.geojson", function (data) {
districts.addData(data);
});
Share
Improve this question
asked Jan 3, 2015 at 5:28
Bergen88Bergen88
1772 gold badges4 silver badges15 bronze badges
1
- I think you forgot to define onEachFeature callback in L.geoJson options. See leafletjs./reference.html#geojson – YaFred Commented Jan 3, 2015 at 18:10
1 Answer
Reset to default 5In onEachFeature callback, you can get the center of the L.Polygon created by GeoJSON layer and bind a label to it.
var polygonCenter = layer.getBounds().getCenter();
// e.g. using Leaflet.label plugin
L.marker(polygonCenter)
.bindLabel(feature.properties['NAME'], { noHide: true })
.addTo(map);
Here is an example: http://jsfiddle/FranceImage/ro54bqbz/ using Leaflet.label