How to highlight one feature on hover from a featureGroup layer?
It's easy when the layer is predefinied and static - I could write a highlighFeature and onEachFeature functions and pass them as options when creating a layer (like in the code created with qgis2web plugin).
But in my code I create line layer inside the code which creates point layer like this:
var linesFeatures = L.featureGroup();
var pointsLayer = L.geoJSON(points, {
pane: 'pointsPane',
pointToLayer: (feature, latlng) => {
const div = document.createElement("div");
div.innerHTML = `${feature.properties.name}<br>`;
const button = document.createElement("button");
button.innerHTML = "Create Line";
button.onclick = function() {
const line1 = L.polyline(
[latlng, [10, 5]],
{color: 'black',})
.bindPopup(feature.properties.name);
linesFeatures.addLayer(line1)
};
div.appendChild(button);
return L.marker(latlng).bindPopup(div);
}
});
linesFeatures.addTo(map);
My first solution based on a highlightFeature from the code created with qgis2web plugin doesn't work and I don't know why:
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
color: 'red'
});
};
function resetHighlight(e) {
var layer = e.target;
layer.resetStyle(e.target);
};
function onEachFeature (feature, layer) {
layer.on({mouseover: highlightFeature,
mouseout: resetHighlight})
};
With these 3 functions above I add onEachFeature inside the code creating a line:
button.onclick = function() {
const line1 = L.polyline(
[latlng, [10, 5]],
{color: 'black',
onEachFeature: onEachFeature
})
.bindPopup(feature.properties.name);
linesFeatures.addLayer(line1)
};
https://jsfiddle.net/nt284j9r/
My second solution with layer.on method works partially, because I want to highlight only a one line on hover and it makes to change color of all the lines from the lines layer. I don't know how to write to make it highlight only one line. I was trying to change var layer to the var feature and passing it as an argument byt it didn' work.
linesFeatures.on('mouseover', function(e) {
var layer = e.target;
layer.setStyle({color: 'green'});
});
linesFeatures.on('mouseout', function(e) {
var layer = e.target;
layer.setStyle({color: 'red'});
});