0
votes

I use Leaflet in Vuejs. I load GeoJSON data on map and I want to highlight a layer(Polygon) when I click on it. That works fine. But when I click on the second layer, I want the first layer to be dehighlighted. Dehighliting of the first layer does not work when I click on second layer. Here is a part of my function which I highlight and try to dehighlight:

 makeEditable(feature, layer) {

    var highlight = {
      'color': '#FFFF00',
      'weight': 2,
      'opacity': 1
    };

    var previouscolor = {
      'color': '#5dbcd2',
      'weight': 2,
      'opacity': 1
    };
    var selected
    var previous
    layer.on('click', function (e) {

        e.target.setStyle(highlight);

        if (selected !== null) {
          previous = selected;
        }

        selected = e.target;

      if (previous) {
        layer.setStyle(previouscolor);
        }
    });
  }

Here is also my computed:

 computed: {
  options() {
    return {
      onEachFeature: this.makeEditable,
    }
  }
}

and I also defined a method to load GeoJSON from DB, which in called in mounted:

  async loadGeoJSON() {
    try {
      this.geojson = await api.getCurrentZones();
    } catch (error) {
      this.error = error.message;
      this.notifyVue();
    }
  },

Any suggestion that how can I dehighlight my layer? enter image description here

1

1 Answers

1
votes

It is easier to mark the selected element with a css class, e.g. with

e.originalEvent.target.classList.add('selected')

(You need originalEvent here, because events are wrapped by leaflet.js with the original DOM event contained in this attribute)

The css class selected can then be defined with normal css, although you need to remember that polygons in leaflet.js are path elements in SVG, so color won't work. Instead, use stroke and fill like that:

.selected {
   stroke: #FFFF00;
   fill: #FFFF00;
}

To unselect a previously selected element, you can use

document.querySelectorAll('.selected').forEach(el => el.classList.remove('selected'))

You should do that before setting the class of the newly selected element.