0
votes

I have a Leaflet map that displays pins from a geojson feed. I want to be able to set custom icons based on an attribute in the geojson that can have one of three values, let's sat Green, Orange, Red, that each have pre-defined custom icons.

If I set

return L.marker(latlng, {icon: Red});

it works fine, but if I set

return L.marker(latlng, {icon: feature.icon});

having verified that the value of feature.icon is Red, it does not work, and returns "Uncaught TypeError: Cannot read property 'popupAnchor' of undefined" relating to a line quite a bit below which is binding a popup to the layer.

I can't help thinking it's a simple syntax error, but cannot work out exactly how I should do this.

I have tried various combinations of single and double quotes, without success.

UPDATE: thanks to the comments and answer below I realised the error in my thinking. I was passing the icon as a text value rather than as an icon object. So the logic to sort this was to test against the text value that was present in the geojson and use that to choose and set the appropriate icon.

1
Without seeing more of your code, it is difficult to help. it seems that feature.icon is not referencing a L.Icon object. How did you instantiate feature.icon ? - YaFred
Ah, thank you, I see what you mean - currently my code has e.g. var Red = L.icon({ iconUrl: 'assets/img/iwm-memorial-red-64.png', iconSize: [30,30], iconAnchor: [25, 24], popupAnchor: [-12, -24] }); but in this instance feature.icon is simply the string 'Red' - jamesinealing
You can see the current code at catchingtherain.com/iwm/… but excuse the messiness! - jamesinealing

1 Answers

4
votes

You have to create all the L.Icon objects you will need and use the onEachFeature callback (see GeoJson) to change the marker icon according to the geojson property.

function onEachFeature(feature, layer) {
  if(feature.properties.icon && feature.properties.icon == "Red") { // Red is the text in the property
    layer.setIcon(Red); // Red is the L.Icon object you have created beforehand
  }
}

See example