1

Using Leaflet with JavaScript I have a map with several GeoJSON Polygon layers.

var assembly = L.geoJSON(null, {onEachFeature: forEachFeature2, style: style2});  
$.getJSON(url2, function(data) {
    assembly.addData(data);
});

I use the onEachFeature's click event to highlight a polygon yellow when clicked. I currently have the layer name with a setStyle(style2) function before the highlight event to clear/reset the previous polygon's style. So I only get one yellow polygon per click and they don't accumulate. While this works I have several layers so each layer has to have it's own onEachFeature function. I'd like to be able to set this layername by code, and have only one onEachFeature function.

function forEachFeature2(feature, layer) {
    layer.on("click", function (e) { 

        assembly.setStyle(style2);  //<<< layername is assembly
        layer.setStyle(highlight);

layer.SetStyle(style2) doesn't work.

`

0

A solution would be to bind your "click" event listener on the GeoJSON layer group, rather than on each individual child feature layer.

That way, e.target gives you access to the group (so that you can reset the style of that group rather than others), and e.layer gives you the individual child feature layer (so that you can highlight it in particular).

assembly.on("click", onFeatureGroupClick);

function onFeatureGroupClick(e) {
  var group = e.target,
      layer = e.layer;

  group.setStyle(style2);
  layer.setStyle(highlight);
}

Example: http://jsfiddle.net/quu3ykp6/8/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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