简体   繁体   中英

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!

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 .

While ideally you would have your geoJSON configured to return at least the initial icon, you can handle this by keeping track of your L.marker objects in a collection, and then calling setIcon() when you need to update the icon.

So let's say you create the marker like this:

const myMarker = L.marker(latlng, {
            'icon': L.icon({
              iconUrl: /example.png
              iconSize: [37, 37],     
              iconAnchor: [18, 37],    correspond to marker's location
            })
          }).addTo(myMap);

Then you can call myMarker.setIcon(newIcon) on your timer event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM