Draw Polygon On Angular Google Map

Draw Polygon On Angular Google Map

In this article, we will learn how to draw a polygon on google map in angular application. In this article we use @agm/core npm package for google map.

So, let's start with implementation,

First we need to create a new angular application using the following command into the terminal.

ng new angular-google-maps

Now, we need to install the @agm/core npm package using the following command into the terminal

npm install @agm/core

Now, we need to import the AgmCoreModule into the app.module.ts file using the following code.

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

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

@NgModule({
  imports: [
    BrowserModule,
    AgmCoreModule.forRoot({
      apiKey: ''
    })
  ],
  providers: [],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Now, add the following code under the app.component.html file.

<agm-map [zoom]="5"
		 [latitude]="lat"
		 [longitude]="lng"
		 (mapReady)="onMapReady($event)">

</agm-map>

Now, add the following code under the app.component.ts file.

import { HttpClient } from '@angular/common/http';

export class AppComponent { lat = 20.5937; lng = 78.9629; drawingManager:any; constructor(private productService: ProductService) { } ngOnInit() { const options = { drawingControl: true, drawingControlOptions: { drawingModes: ['polygon'], }, polygonOptions: { draggable: true, editable: true, }, }; this.drawingManager = new google.maps.drawing.DrawingManager(options); setCurrentPosition(); } private setCurrentPosition() { if ('geolocation' in navigator) { navigator.geolocation.getCurrentPosition((position) => { this.lat = position.coords.latitude; this.lng = position.coords.longitude; }); } } onMapReady(map) { this.initDrawingManager(map); } }

Now, add the following code under the app.component.css file to set the size of map.

agm-map {
 height: 400px;
}

Now, run the application and see the browser screen look's like below.

Draw Polygon On Angular Google Map

Conclusion

In this article, we learned how to draw a polygon on google map in angular application using the @agm/core npm package.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post