[GIS] Leaflet ‘Click’ event on line portion

geojsonjavascriptleafletline

I have a polyline as GeoJSON layer in Leaflet.

I need a JavaScript event when the user click on the portion of the line.

I have to highlight the selected line segment. Is it possible this?

Best Answer

Here is the basic idea, set a style for the line, and set a style for the highlight, then in your forEachFeature function, set the layer on click to highlight. My example below resets the style in case, you clicked on one before.

var highlight = {
    'fillColor': 'yellow',
    'weight': 2,
    'opacity': 1
};

    function forEachFeature(feature, layer) {

        layer.on("click", function (e) { 
            stateLayer.setStyle(style); //resets layer colors
            layer.setStyle(highlight);  //highlights selected.
        }); 
    }

Here is a working example for a polygon layer. http://www.gistechsolutions.com/leaflet/DEMO/basic/basic_Poly.html