Leaflet Polyline – How to Make Leaflet Polyline Bold on Hover with JavaScript

javascriptjqueryleaflet

I have a Leaflet map that I show streets and also there is an unordered list of street names in the same page with map. What I want to do is when mouse cursor hovers on a street name in the list, the poly-line which belongs to that street should be bold.

As far as I know, there is no method listed for Leaflet like that by default but there are options for poly-lines for styling and mine could be shown as below:

var polyline = L.polyline(latlngs, {weight: 6}).addTo(map);

How can I apply the bold styling to my poly-lines on a hover event?

Best Answer

There is no bold style for polylines, just weight option, which is width of polyline in pixels.

If you want to change polyline style to 'bold', you have to increase it's width, let's say from 6 to 8 pixels. You can increase it's width by declaring mouseover event catch function, where you can change width of polyline by setStyle method.

At the same time you have to save original weight to dummy mySavedWeight property (name can be any, as long as it's not in conflict with standard names), which is then used in mouseout catch function to return style to original one when mouse leaves polyline. Since there is no getStyle method for polyline, width can be saved via options property.

Code could then look something like this:

var polyline = L.polyline(latlngs, {weight: 6}).addTo(map);

polyline.on('mouseover', function() {
  this.mySavedWeight = this.options.weight;
  this.setStyle({
    weight: 8
  });
});

polyline.on('mouseout', function() {
  this.setStyle({
    weight: this.mySavedWeight
  });
});