2

I'm referencing external data, matching it up with particular fields in feature.properties and using that to decide which layer to put the feature in, all of this from inside the onEachFeature part.

onEachFeature: function(feature, layer) {
...
if (condition1)
  layer.addTo(layer1);
else if (condition2)
  layer.addTo(layer2);
else ...
}

I want to set different icons / markers also in the same process. But I see that custom markers are usually set in the pointToLayer part, like:

pointToLayer: function (feature, latlng) {
  ..
  if(condition1) return L.marker(latlng, {icon: icon1});
  else if(condition2) return L.marker(latlng, {icon: icon2});
  else ...
}

(assume that icon1 and icon2 have already been defined as new L.icon({ .... }) )

It's going to get really repetitive and processor/network-consuming to reference the external data all over again in pointToLayer.

Is there a way I can define the feature's icon from the onEachFeature part itself and not have to go through pointToLayer ?

And even the other way around :

Is it possible to do the things you'd normally do in onEachFeature, in pointToLayer instead?

The layer argument isn't there in most uses.. can it be passed in?

Does leaflet loop through each feature for pointToLayer the same way it does for onEachFeature ?

1

1 Answer 1

3

Maybe this can help.

Use the setIcon method in each condition:

onEachFeature: function(feature, layer) {
...
if (condition1) {
  layer.setIcon(icon1);
  layer.addTo(layer1);
}
else if (condition2) {
  layer.setIcon(icon2);
  layer.addTo(layer2);
}
else ...
}
2
  • So I guess this means each different Icon Style has to go in a separate layer? Is there a way of having multiple icon styles in the one layer?
    – LeasMaps
    Commented Sep 2, 2018 at 4:59
  • 1
    @LeasMaps sure, just do layer.addTo(layer1) everywhere. They'll all be in the same layer then.
    – Nikhil VJ
    Commented Sep 2, 2018 at 9:54

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.