In my application, I use Angular Google Maps (AGM) to build a map. How can I draw a polygon on it? I followed the solution described in https://stackblitz.com/edit/agm-polygon but some directives are missing. How can I enable the drawing manager on the AGM map and draw polygons like in the example?
This is the import in the app.module:
AgmCoreModule.forRoot({
apiKey: 'key',
language: localStorage && localStorage.defaultLang || 'el',
libraries: ['places', 'drawing', 'geometry']
})
You most likely getting errors related with agm-drawing-manager
component, right? It appears agm-drawing-manager
directive which is utilized in the provided demo is no longer part of angular-google-maps
library (1.0.0-beta.5
version) and thatäs the reason why those errors occur.
To enable Google Maps drawing tools the following solution could be considered (adapted from official example):
app.component.html
<agm-map [latitude]="center.lat" [longitude]="center.lng" (mapReady)="onMapReady($event)">
</agm-map>
app.component.ts
import { Component } from "@angular/core";
declare const google: any;
@Component({
selector: "app-map",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
center: any = {
lat: 33.5362475,
lng: -111.9267386
};
onMapReady(map) {
this.initDrawingManager(map);
}
initDrawingManager(map: any) {
const options = {
drawingControl: true,
drawingControlOptions: {
drawingModes: ["polygon"]
},
polygonOptions: {
draggable: true,
editable: true
},
drawingMode: google.maps.drawing.OverlayType.POLYGON
};
const drawingManager = new google.maps.drawing.DrawingManager(options);
drawingManager.setMap(map);
}
}
It could be further improved by introducing, for example, a separate directive for google.maps.drawing.DrawingManager
class
Prerequisites
In app.module.ts
don't forget to load drawing
package via AgmCoreModule module:
AgmCoreModule.forRoot({
apiKey: "--YOUR-GOOGLE_MAPS_KEY-GOES-HERE--",
libraries: ['drawing']
})
Here is a demo for your reference