How to get polyline coordinates React-Leaft-Draw plugin?

Viewed 129
1 Answers

I agree, the documentation is a bit lacking, so I hope this helps anyone else trying to do this. You first implement an onCreated function that is registered on the <EditControl> component. You can then access the current layer object and its layerType from the event object that gets passed to this callback.

Depending on the shape type, you can access the coordinates of the shape via a the methods provided by Leaflet (e.g. circle). See code below.

export default DrawTool({prop1, prop2) {
  
  const onCreated = (e) => {
    if (e.layerType === 'circle') {
      console.log("circle center, radius =", e.layer.getLatLng(), e.layer.getRadius())
    } else {
      // polygon & rectangle
      console.log("polygon coordinates =", e.layer.getLatLngs()) // array of LatLng objects
    } // marker or lines, etc.
    // map.addLayer(e.layer) // might need?
  }

  const onDelete = (e) => {
    // do something with e.layer
  }

  return (
    <EditControl
      position='topright'
      onCreated={onCreated}
      onDeleted={onDeleted}
      ...
    />
  )
}
Related