Search code examples
javascriptleafletgeojsonkmlreact-leaflet

Calling methods on React-Leaflet components (LayerGroup)


I am trying to call the method toGeoJSON on my React-Leaflet LayerGroup. (Ultimately I am trying to convert the layer group into KML, but I found the answer here, and I am first trying to convert it into geoJSON)

I tried adding a ref to the LayerGroup and then calling toGeoJSON on it, but it fails as that is not a function. When inspecting the ref for the LayerGroup, it doesn't seem to have any of the methods available in the leaflet documentation

Is there a way around this? I have Leaflet and ReactLeaflet libraries imported and in scope of the function, I'm just not sure how to find that function.

Simplified version of my code:

function MyMap(){
  const markerRef = useRef()

  function export(){
    let markers = markerRef.current
    let GeoJSON = markers.toGeoJSON() // < THIS LINE THROWS AN ERROR
  }

  return (
    <>
      <button onClick={export}>Export</button>
      <Map>
        <LayerGroup ref={this.markersRef}>{markers}</LayerGroup>
      </Map>
    </>
  )
}

More thorough example: https://codesandbox.io/s/react-lealfet-map-bug-report-4258z


Solution

  • Just needed to access markers.leafletElement.toGeoJSON(). Leaflet methods can be accessed through leafletElement.

    oops