0

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.

3
  • 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
    Commented Jun 10, 2016 at 19:14
  • 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' Commented Jun 10, 2016 at 19:22
  • You can see the current code at catchingtherain.com/iwm/… but excuse the messiness! Commented Jun 10, 2016 at 19:27

1 Answer 1

4

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

1
  • Perfect, thank you. I had a similar thought after I went to bed last night and using this I have implemented it in the form if(feature.icon && feature.icon == "Red") { myIcon = memorialIconRed; } else if(feature.icon && feature.icon == "Orange") { myIcon = memorialIconOrange; ... Commented Jun 11, 2016 at 15:57

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