I am attempting to create my first leaflet map. I am using OpenStreetMap tiles and adding geojson features as overlay layers. I have been following tutorials with much success, until I started trying to add labels. I would simply like to add static labels to several features, and be able to toggle them on/off with the layer control. I have been using leaflet.label. Is this possible?
I have tried the following to give me labels with mixed results:
function onEachFeature(feature, layer) {
if (feature.properties && feature.properties.name) {
<!-- shows label only on mouseover -->
//layer.bindLabel(feature.properties.name, { 'noHide': true});
<!-- creates static labels, but remain when layers are turned off -->
//var label = new L.Label();
//label.setContent(feature.properties.name);
//label.setLatLng(layer.getBounds().getCenter());
//map.showLabel(label);
}
}
Here is my layer control:
var overlayMaps = {
"Layer 1": L.geoJson(layer1geojson, {onEachFeature: onEachFeature}).addTo(map),
"Layer 2": L.geoJson(layer2geojson, {onEachFeature: onEachFeature}).addTo(map),
"Buildings": L.geoJson(buildingsGeojson, {onEachFeature: onEachFeature}).addTo(map)
};
var legend = L.control.layers(baseMaps, overlayMaps, {collapsed:false});
legend.addTo(map);
UPDATE
I used the following technique proposed by ghybs to add labels to geojson features and have the ability to turn them off with the layer control.
var buildingGroup = L.layerGroup().addTo(map);
L.geoJson(buildings, {
style: buildingStyle,
onEachFeature: function(feature, layer) {
var label = new L.Label();
label.setContent(feature.properties.name);
label.setLatLng(layer.getBounds().getCenter());
buildingGroup.addLayer(layer);
buildingGroup.addLayer(label);
}
});
// Repeat for any additional layers with labels
// Add Group to overlays
var overlays = {
"Layer1": layer1Group,
"Layer2": layer2Group,
"Buildings": buildingGroup
};
// Add layer control to map
L.control.layers(baseMaps, overlays, {collapsed:false}).addTo(map);