Search code examples
javascriptimageiconsleafletgeojson

leaflet - Changing marker node icon


This is the GeoJSON point I have:

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [
      "-83.882517",
      "32.55514717"
    ]
  },
  "properties": {
    "popupContent": "\u003cb\u003eStart OS:(2018-01-25-06.10.46.140000 )\u003c/b\u003e\u003cbr/\u003e(-83.882517, 32.55514717)\u003cbr/\u003e",
    "style": {
      "radius": 8,
      "weight": 1,
      "color": "#000033",
      "fillColor": "#FFFF00",
      "opacity": 1,
      "fillOpacity": 1
    },
    "icon": null
  },
  "id": 5001
},

Now, as you see the element has "icon": null. How can I access the specific element and change its icon (with something like XXX.setIcon(trainIcon);)?

I don't understand how to access the single element and change some of its values. All the feature points are part of the same layer.

Thank you!


Solution

  • If I understand correctly, you have GeoJSON data that you display on a Leaflet map by feeding it to L.geoJSON factory.

    But in some cases, your GeoJSON data does not specify a proper icon in the Feature properties, hence you would like to modify those.

    Of course the ideal would be to fix your GeoJSON data beforehand, instead of trying to fix the situation at runtime. But if for whatever reason you cannot modify the GeoJSON data, you still have several possible solutions with Leaflet:

    1. Use the onEachFeature option of L.geoJSON factory, test if the feature.properties.icon is incorrect, then reassign the marker icon.

    2. Use the eachLayer method of your already created L.geoJSON Layer Group, test if the layer.feature.properties.icon is incorrect, then reassign the marker icon.

    Since your Features also have an ID, if you know the ID of the Features you need to rework, you could also test for this ID instead of properties.icon.