TransWikia.com

Putting different id in different paths on my Leaflet map

Geographic Information Systems Asked by Rayssa Rocha on February 2, 2021

I have many polygons to display on map like this:

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

and each polygon generate a <path> like this

<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>

Is there a way that I can put a different id for each path?

One Answer

Leaflet offers no way of assigning HTML id attribute to HTML path elements that represent vector layer feature. But since you just want a way to select desired path elements from the DOM structure, there is a bit hacked way to do that.

One of the Leaflet style options is className, which can be any string. This class name is then added to the path element class list. There is no harm if such CSS class actually does not exist, it will be just "misused" to get collection of desired path elements with the document.getElementsByClassName method.

If in your case you would want to get all elements where feature.color has value 'red', your code could look something like this:

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

.
.
.

var red_elements = document.getElementsByClassName('id_red');

Answered by TomazicM on February 2, 2021

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