MAYANK KUMAR
MAYANK KUMAR

Reputation: 408

How do I extract data from Drawing Manager in react google maps?

Hi I am making an app which uses google maps to select some location.

I am using Drawing Manager of google map to draw a polygon.

Now I want to get the coordinates of the polygon.

Is there any way to do it?

Here is the code:

 <DrawingManager
    defaultDrawingMode={window.google.maps.drawing.OverlayType.POLYGON}
    defaultOptions={{
      drawingControl: true,
      drawingControlOptions: {
        position: window.google.maps.ControlPosition.TOP_CENTER,
        drawingModes: [
          window.google.maps.drawing.OverlayType.MARKER,
          window.google.maps.drawing.OverlayType.POLYGON,
        ],
      },
      polygonOptions: { editable: true },
    }}
  />

Upvotes: 0

Views: 817

Answers (2)

ShresthaDGaurav
ShresthaDGaurav

Reputation: 1

const [LocationList, setLocationList] = useState([]); //define state
    
//method to store location in state
const onPolygonComplete = (polygon) => {
        setLocationList(
          polygon
            .getPath()
            .getArray()
            .map((point) => ({
              lat: point.lat(),
              lng: point.lng(),
            }))
        )}
// define component
      <DrawingManager
      onPolygonComplete={onPolygonComplete}//link method
    />

Upvotes: 0

Pagemag
Pagemag

Reputation: 2977

You can add a listener to the drawing manager for the "polygoncomplete" event then you can use the getPath() method to get the coordinates. If you are using a reactjs library for google maps, you can check how that library is using the polygoncomplete event. Here is a snippet where I put all the points from the polygon.getpath().getArray() to the array and log it in the console in a simple code:

          const drawingManager = new google.maps.drawing.DrawingManager({
            drawingMode: google.maps.drawing.OverlayType.MARKER,
            drawingControl: true,

            drawingControlOptions: {
              position: window.google.maps.ControlPosition.TOP_CENTER,
              drawingModes: [
                window.google.maps.drawing.OverlayType.MARKER,
                window.google.maps.drawing.OverlayType.POLYGON
              ]
            },
            polygonOptions: { editable: true }
          });
          drawingManager.setMap(map);

          google.maps.event.addListener(
            drawingManager,
            "polygoncomplete",
            function(polygon) {
              let polygonCoordsArray = [];
              let coords = polygon.getPath().getArray();

              for (let i = 0; i < coords.length; i++) {
                // console.log(coords[i].lat() + "," + coords[i].lng());
                polygonCoordsArray.push(
                  coords[i].lat() + "," + coords[i].lng()
                );
              }
              console.log(polygonCoordsArray);
            }
          );

Upvotes: 1

Related Questions