How to draw a shape of polygon dynamically on map in Angular
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 plunker:
Basic version (drawing polygon only) https://stackblitz.com/edit/angular-draw-polygon-google-maps
Updated version (draw polygon and intersect checking) (plunker is not working now) https://embed.plnkr.co/3sNWwX/
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());
}
});
})
}
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