Furqan S. Mahmoud
Furqan S. Mahmoud

Reputation: 1455

How to get the coordinates of a drawn ploygon using angular google maps (AGM)

I'm working on a feature where the user should be able to draw a polygon and store the polygon coordinates into the system so I can show it later on the map. I implemented the drawing feature here: https://stackblitz.com/edit/angular-ptjb9t?file=src%2Fapp%2Fapp.component.html

but how can I get the coordinates "points(lat,lng)" of that polygon?

thanks

Upvotes: 0

Views: 1156

Answers (1)

Furqan S. Mahmoud
Furqan S. Mahmoud

Reputation: 1455

I figured it out by listening to polygoncomplete event, from that you can get the polygon coordinates as shown below:

google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) {
  const len = polygon.getPath().getLength();
  const polyArrayLatLng = [];

  for (let i = 0; i < len; i++) {
    const vertex = polygon.getPath().getAt(i);
    const vertexLatLng = {lat: vertex.lat(), lng: vertex.lng()};
    polyArrayLatLng.push(vertexLatLng);
  }
  // the last point of polygon should be always the same as the first point (math rule)
  polyArrayLatLng.push(polyArrayLatLng[0]);


  console.log('coordinates', polyArrayLatLng);
});

stackblitz, references: google maps documentation

Upvotes: 1

Related Questions