[GIS] Changing marker icon from onEachFeature instead of pointToLayer using Leaflet

iconlayersleafletmarkers

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 ?

Best Answer

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