Angular Google Maps Get Current Location – Latitude, Longitude on Click Event

Today, You will learn how to get the current location in Angular Google maps. We will discuss getting current coordinates including the latitude-longitude on click even on google maps in the Angular app. In this example, you will get the complete address a coordinate using the Geocoder service using Google API.

This Angular post is compatible with Angular 4 upto latest versions, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11 & Angular 12

By using the AGM core library package, you can easily add the Google Maps component to your angular application. We will go through step by step to integrate the Google map and get current coordinates on clicking anywhere on the map. You just need to follow few easy steps to create a Google map with a zoom feature and place a search bar as shown below.

How to get Lattitude and Longitude on Clicking the Google Map?

Let’s go through the following easy steps to integrate Google Maps in the Angular app…

 

Step 1 – Create Angular Application

To begin with, create a new angular application by executing the below command:

$ ng new angular-google-map-app

Then, move inside the application directory:

$ cd angular-google-map-app

Step 2 – Install AGM/Core Package

Next, we need to install the AGM code library package by executing the below npm command:

$ npm install @agm/[email protected] --save

We also need to install the type for the google maps library. So, execute below npm type package as well:

$ npm install @types/googlemaps --save-dev

Thereafter, open the tsconfig.app.json file, then add the "googlemaps" under the types array property:

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [
      "googlemaps"
    ]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

Step 3 – Update App Module with AgmCore Module

Next, we will import the AgmCoreModule then add into the imports array. After that, we will be able to use Google maps in our Angular application.

Google API Key: You also need to specify the Google API key in the App Module. You need to visit the Google Console, then create the API key.

Let’s open the app.module.ts file then update it as shown below:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { AgmCoreModule } from '@agm/core';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    AgmCoreModule.forRoot({
      apiKey: 'GOOGLE API KEY',
      libraries: ['places']
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4 – Update Component Class

Now, define the variable to keep latitude and longitude values. Head towards the app.component.ts file and update the following code:

//app.component.ts

import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { MapsAPILoader } from '@agm/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title: string = 'AGM project';
  latitude!: number;
  longitude!: number;

  @ViewChild('search')
  public searchElementRef!: ElementRef;


  constructor(
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone
  ) { }


  ngOnInit() {
    //load Places Autocomplete
    this.mapsAPILoader.load().then(() => {
    });
  }

  onMapClicked(event: any){
    console.table(event.coords);
    this.latitude = event.coords.lat;
    this.longitude = event.coords.lng;
  }

}

Above the onMapClicked event will be triggered on clicking on the map on any area to return the Object carrying latitude, longitude and other information.

Step 5 – Update HTML Template

Now open the app.component.html file and add the following template HTML:

<!-- app.component.html -->
<div class="container">

  <h1>Angular Google Maps - Get Latitude and Longitude on Click</h1>

  <agm-map [latitude]="latitude" [longitude]="longitude" (mapClick)="onMapClicked($event)">
  </agm-map>

  <div>Latitude: {{latitude}}</div>
  <div>Longitude: {{longitude}}</div>
</div>

The (mapClick) event will return the current coordinates on clicking on google map.

Step 6 – Run Application

Finally, run the application by hitting the following command:

$ ng serve --open

It will the application at following URL

http://localhost:4200

Conclusion

We discussed how to add Google maps in the Angular application and fetch coordinates on clicking any area on Google Maps to address as well.

 

Leave a Reply

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