TransWikia.com

Changing style of only selected polygons in L.geoJSON layer?

Geographic Information Systems Asked on December 18, 2020

So, I’m going to show a lot of polygons in my Leaflet map but I need an id for each polygon, the URL comes in a path like this.

In fact I wouldn’t even need an id, if I could somehow get some properties like that, like stroke = red would work for me, because I want to change a property when the path is in red.

<path class="leaflet-interactive" stroke="red" stroke-opacity="0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="red" fill-opacity="0" fill-rule="evenodd" d="M477 171L469 171L468 176L455 175L455 171L459 171L461 167L465 167L467 163L471 163L472 160L479 153L488 148L493 147L494 158L489 159L487 163L477 167L477 171z"></path>

My code for all polygons

 L.geoJSON(polygon, {
        style: function (feature) {
          return {
            stroke: true,
            fillColor: feature.color,
            fillOpacity: feature.opacity,
            color: feature.color,
            opacity: feature.opacity,
            weight: 2,
          };
        },
      })
        .bindPopup(function (layer) {
          return layer.feature.properties.name;
        })
        .addTo(map); 

and the function that will change, but in this way is not working

      case 3:
        const elm3 = d3.selectAll(`g path[style = "fill: red"]`);
        elm3.style('opacity', checked ? 0 : 0.7);

        break;

One Answer

It would be simpler to let Leaflet do the desired change in style through the style option.

Set initial opacity for features which have the desired color with the style function to some predefined value:

redOpacity = 0;

function myStyle(feature) {
  var opacity = (feature.color == 'red') ? redOpacity : feature.opacity;
  return {
    stroke: true,
    fillColor: feature.color,
    fillOpacity: opacity,
    color: feature.color,
    opacity: opacity,
    weight: 2,
  };
}

myGeoJSON = L.geoJSON(polygon, {
  style: myStyle,
})
.bindPopup(function (layer) {
  return layer.feature.properties.name;
})
.addTo(map);

Then when needed simply change this value and set style function again with setStyle method to refresh layer style:

redOpacity = 0.7;
myGeoJSON.setStyle(myStyle);

Correct answer by TomazicM on December 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP