2

I am trying to figure out how to highlight multiple polygons/features based on the feature.properties.NAME value. My polygons are a bit broken up so they are separate features and using an onEachFeature function will only highlight the specific shape mouseover as opposed to all of them with the same name.

// current function being used to highlight
function onEachFeature(feature, layer) {
  layer.on('mouseover', () => {
      layer.setStyle({
        weight: 4,
        opacity: 0.7
      });
    }),
    layer.on('mouseout', () => {
      layer.setStyle({
        weight: 1,
        opacity: 0.85
      });
    })
}

For example here is a sample jsfiddle. When mousing over a "SHAPE-A" polygon it should highlight the 3 (top, top left, bottom right) and mousing over "SHAPE-B" should highlight the 2 (right, bottom left).

1 Answer 1

0

One possible solution would be to use mouseover event processing function to store name of the feature to global variable highlightedName. This name can be then used in the style function to set highlight style when name of the feature equals stored global name. Also .setStyle method has to be explicitly used to change the layer style when variable highlightedName is set.

Your code could then look something like this:

var highlightedName = null;

function mapStyle(feature) {
  var weight, opacity;
  if (feature.properties.NAME == highlightedName) {
    weight = 4;
    opacity = 0.7;
    }
  else {
    weight = 1;
    opacity = 0.85;
  }
  return({
    color: "#1890ff",
    weight: weight,
    opacity: opacity
  });
}

function onEachFeature(feature, layer) {
  layer.on('mouseover', () => {
    highlightedName = feature.properties.NAME;
    vectorLayer.setStyle(mapStyle);
  }),
  layer.on('mouseout', () => {
    highlightedName = null;
    vectorLayer.setStyle(mapStyle);
  })
}

var map = L.map('map', mapOptions).setView([0, 0], 3);

var vectorLayer = L.geoJSON(basemap, {
    style: mapStyle,
    onEachFeature: onEachFeature
  })
  .bindTooltip(function(layer) {
    return layer.feature.properties.NAME;
  });

map.addLayer(vectorLayer);
map.fitBounds(vectorLayer.getBounds());
2
  • this possible with vector grid .pbf files?
    – ziggy
    Oct 23, 2022 at 1:41
  • Not enough info to answer that. Post it as a separate question with all the necessary info.
    – TomazicM
    Oct 23, 2022 at 7:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.