Assign ID to marker in leaflet

后端 未结 7 1082
忘了有多久
忘了有多久 2020-12-23 11:47

So i try to achieve a result as on foursquare: https://foursquare.com/explore?cat=drinks&mode=url&near=Paris which is when you clik on a marker on the map, it scrol

7条回答
  •  独厮守ぢ
    2020-12-23 12:23

    For my case, I found the best way was to generate and pass a unique ID to L.marker's Options object when I create it.

    const newMarker = L.marker([lat, lng], { uniqueID })
    

    You can then add this marker to a leaflet layerGroup.

    const newLayerGroup = L.layerGroup().addTo(map);
    newLayerGroup.addLayer(newMarker);
    

    You can access the ID with layer.options.uniqueID This allows me to find and manipulate the marker later; all I need is Leaflet's .eachLayer() and the uniqueID.

    My backend (Cloud Firestore) already generates unique document ID's, which makes it super easy to sync my Leaflet map and backend in real-time, rather than rebuilding and remounting the entire layerGroup or refreshing the page.

    //e.g. a callback which fires whenever a doc has been removed from my db
    
    newLayerGroup.eachLayer((layer) => {
      if (deletedDocID === layer.options.uniqueID) {
        newLayerGroup.removeLayer(layer);
      }
    });
    

提交回复
热议问题