Add Google Map Using agm/core In Angular With Example

You can easily integrate google map in your angular applications using agm/core

If you have a requirement where you need to add google map and other features of google map such as add marker, pick latitude and longitude,
you can easily do such thing using agm/core package. 

If you can also pick machine's location using navigator and set that location in google map as initial current coordinates.

Let's understand google map integration using agm/core in various steps.

Step1: Install agm/core npm package using below command


	npm install @agm/core --save 

We also need google map library so let's install that also using below command

    npm install @types/googlemaps --save-dev

Step 2: Open your tsconfig.app.json file from root folder and add "googlemaps" in type array as below.

Step 3: Import AgmCoreModule in your app module, here we also specify Google Map Api Key in import array, you can easily generate 
google api key from Google Console. so let's import AgmCoreModule in our app module as below:


	import {AgmCoreModule} from '@agm/core';
	
	@NgModule({

		  imports: [
			AgmCoreModule.forRoot({
			  apiKey: 'YOUR GOOGLE API KEY',
			  libraries: ['places']
			})
		]
	})

Step 4: Let's add some more line's in component ts file.


	import { Component } from '@angular/core';
   
	@Component({
	  selector: 'app-root',
	  templateUrl: './app.component.html',
	  styleUrls: ['./app.component.css']
	})
	export class AppComponent {	  
	  latitude: number = 28.56133450;
	  longitude: number = 77.34949913;
	  zoom: number = 14; // zoom level of google map
	}

Step 5: Let's add agm-map tag in HTML file of component as below

<agm-map [latitude]="latitude" [longitude]="longitude" [zoom]="zoom">
          <agm-marker [latitude]="latitude" [longitude]="longitude" [markerDraggable]="true" (dragEnd)="markerDragEnd($event)">
          </agm-marker>
    </agm-map>
	

we specify "markerDraggable"  as true to allow draggeble marker on map and once you put marker at specify place of google map,
markerDragEnd method will execute and you will get new coordinates as below:


	markerDragEnd($event: MouseEvent) {
		this.latitude = $event.coords.lat;
		this.longitude = $event.coords.lng;
	  }

Additionally, if you need machine's location using navigator you can use below lines and add in your component file.


	ngOnInit(): void {
		this.setCurrentLocation();
	  }
	  
	  private setCurrentLocation() {
		if ('geolocation' in navigator) {
		  navigator.geolocation.getCurrentPosition((position) => {
			this.latitude = position.coords.latitude;
			this.longitude = position.coords.longitude;
		  });
		}
	  }  

Hope you will find this helpful, write us below to improve article.

Thank you for reading :) Please subscribe our newsletter to get updates for new articles

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *
Phone