Angular 14 Get Current Location Latitude and Longitude

Angular 14 gets the current location latitude and longitude; Through this tutorial, you will learn how to get the current location latitude and longitude in Angular 14 Google maps by using the google AGM core package.

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

Use the following steps to integrate Google Maps in the Angular 14 aps; as follows:

Step 1 – Create Angular Application

Execute the following command on terminal to 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

Then execute the following command on terminal to install the AGM code library package by executing the below npm command:

$ npm install @agm/core@1 --save

Then execute the following command on termainal 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

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>Copy

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

Recommended Angular Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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