Ratan Uday Kumar
Ratan Uday Kumar

Reputation: 6482

How to draw a shape of polygon dynamically on map in Angular

how to draw a shape of polygon dynamically(not predefined paths) and how to store lat long values of Polygon

I already refer AGMPolygon but it didn't solve my isuse

Upvotes: 12

Views: 15862

Answers (2)

trungvose
trungvose

Reputation: 20034

Update 26 Apr 2018.

I am not sure but seems that the Angular Google Maps has already supported drawing polygon. You can check more.


Check the working demo:

  1. Basic version (drawing polygon only) https://stackblitz.com/edit/angular-draw-polygon-google-maps

  2. Updated version (drawing multiple polygon and intersect checking) https://stackblitz.com/edit/angular-draw-polygon-intersect?file=src/main.ts

AGM is the best library for Angular 2 for now but It still needs to update more to reflect all the Google Maps API. So better we follow Google Maps doc and use it directly before the Angular community support it.

https://developers.google.com/maps/documentation/javascript/examples/drawing-tools

Please be noted that it is a very basic one which allows you to draw a polygon and get the coordinate once finishing. You might want to move all the map related code into service as well.

Also, better to wrap the whole code within zone.runOutsideAngular to prevent unnecessary change detection.

constructor(private zone: NgZone) {

}

ngOnInit() {
    this.zone.runOutsideAngular(() => {
      this.map = new google.maps.Map(document.getElementById('map'), {
          center: { lat: -34.397, lng: 150.644 },
          zoom: 8
      });

      this.drawingManager = new google.maps.drawing.DrawingManager({
          drawingMode: google.maps.drawing.OverlayType.POLYGON,
          drawingControl: true,
          drawingControlOptions: {
              position: google.maps.ControlPosition.TOP_CENTER,
              drawingModes: ['polygon']
          }
      });

      this.drawingManager.setMap(this.map);
      google.maps.event.addListener(this.drawingManager, 'overlaycomplete', (event) => {
          // Polygon drawn
          if (event.type === google.maps.drawing.OverlayType.POLYGON) {
            //this is the coordinate, you can assign it to a variable or pass into another function.
              alert(event.overlay.getPath().getArray());
          }
      });
    })        
}

Upvotes: 16

Rishabh Agrawal
Rishabh Agrawal

Reputation: 111

Refer to this and try to implement using javascript. The Code will be much simpler (i personally prefer this) https://developers.google.com/maps/documentation/javascript/examples/drawing-tools

Upvotes: 4

Related Questions