Tuesday, October 8, 2024
Google search engine
HomeLanguagesAngularAngular 16 Google Maps Get Current Location Latitude and Longitude Example Tutorial

Angular 16 Google Maps Get Current Location Latitude and Longitude Example Tutorial

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

Angular 16 Google Maps Get Current Location Latitude and Longitude

Steps to integrate Google Maps and get current location, latitude, and longitude while clicking on google map in angular 16 projects:

  • Step 1 – Set Up the Angular Project
  • Step 2 – Install AGM/Core Package
  • Step 3 – Configure Google Maps API Key
  • Step 4 – Include AgmCore Module and Google Api Key
  • Step 5 – Update Component Class
  • Step 7 – Implement Google Map in HTML Template
  • Step 6 – Run the Application

Step 1 – Set Up the Angular Project

First of all, open your cmd or command prompt and execute the following command into it to install and new Angular project using the Angular CLI:

ng new angular-google-maps-demo
cd angular-google-maps-demo

Step 2 – Install AGM/Core Package

Next, execute the following command on cmd to install the AGM code library package by executing the below npm command:

npm install @agm/core@1 --save

Once you have done the above things. Now, you need to execute the following command on cmd to install the type for the google maps library. So, execute the 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 – Configure Google Maps API Key

To use Google Maps services, you need to obtain an API key from the Google Cloud Console. Follow these steps to get your API key:

  1. Go to the Google Cloud Console: https://console.cloud.google.com/
  2. Create a new project or select an existing one.
  3. Enable the “Maps JavaScript API” for your project.
  4. Create an API key.
  5. Restrict the API key if desired (optional, but recommended for security).

Step 4 – Include AgmCore Module and Google Api Key

Next, you ned to import the AgmCoreModule and google map api key in app.module.ts.

Let’s open the app.module.ts file and then add 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 5 – Update Component Class

Next, define the variable to keep latitude and longitude values. So, open app.component.ts file and add 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 6 – Implement Google Map in HTML Template

Next, 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 7 – Run the Application

Finally, execute the following command on cmd to start the Angular development server:

$ ng serve --open

Once the server is up and running, open your web browser and navigate to http://localhost:4200. You should see the map centered at your current location, and a marker indicating that location.

Conclusion

Congratulations! You have successfully implemented an Angular application that displays a map and retrieves the user’s current location latitude and longitude using the Google Maps JavaScript API.

Recommended Angular Tutorials

RELATED ARTICLES

Most Popular

Recent Comments