How To Draw A Polygon Using @agm-core In Angular

In this article, we will learn how to draw a polygon using @agm-core in angular

Let’s get started with creating angular project using below command.

ng new my-maps-project

Install Angular Google Maps

You need to execute below code to install a @agm/core package.

npm install @agm/core

Setup @NgModule

You need to provide a Google Maps API key to be able to see a Map. Get an API key here

Now open app.module.ts file and import AgmCoreModule like below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AgmCoreModule } from '@agm/core';

import { AppComponent } from './app.component';

  imports: [
      apiKey: ''
  providers: [],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
export class AppModule {}

Now create a component using below command

ng g c agm-demo

Once component is created, Add below HTML code

<agm-map [zoom]="5" [latitude]="lat" [longitude]="lng"> </agm-map>

Now add lat and lng with valid values in the ts file.

lat = 20.5937;
lng = 78.9629;

You can also set the lat and lng as your current location by calling the following function inside ngOnInit()

private setCurrentPosition() {
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => { = position.coords.latitude;
        this.lng = position.coords.longitude;

Set height of map

agm-map {
 height: 400px;

Now add mapReady event

<agm-map [zoom]="5" [latitude]="lat" [longitude]="lng"

Define onMapReady() function as shown below, to initialize the drawing manager.

onMapReady(map) {

Initialize drawingManager

const options = {
 drawingControl: true,
 drawingControlOptions: {
  drawingModes: ['polygon'],
 polygonOptions: {
  draggable: true,
  editable: true,
 drawingMode: google.maps.drawing.OverlayType.POLYGON,
this.drawingManager = new google.maps.drawing.DrawingManager(options);

Also you set below event that execute after draw polygon

  • overlaycomplete
    Set on the drawing manager. It is invoked whenever a closed polygon is created on the map.


Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories