Wednesday, 15 March 2023

How to get our current location in formatted text using Angular and google map api

Get Current Location Using Angular and Google Maps API - Step-by-Step Tutorial

Hi Everyone, hope you all are doing well.

  1. Introduction: how web applications that use location data can provide users with more personalized and relevant experiences. For example, a weather app could display the current weather conditions based on the user’s location, or a restaurant review app could show nearby restaurants based on the user’s current location. we can also highlight the benefits of using the Google Maps Geocoding API, such as its accuracy and speed.

a. Create a new Angular project by running the following command in your terminal:
ng new location-app
b. Navigate to the project directory:
cd location-app
c. Open the project in your code editor:
code .
d. In the app.component.html file, add the following code:

<button (click)=”locateMe()”>Locate Me</button>

<br>

<input type=”text” [value]=”address”>

This code creates a “Locate Me” button and an input box to display the formatted address.

e. In the app.component.ts file, add the following code:

import { Component } from ‘@angular/core’;

import { GeocodingService } from ‘./geocoding.service’;

@Component({

selector: ‘app-root’,

templateUrl: ‘./app.component.html’,

styleUrls: [‘./app.component.css’]

})

export class AppComponent {

address = ‘’;

constructor(private geocodingService: GeocodingService) { }

locateMe() {

navigator.geolocation.getCurrentPosition(position => {

const latitude = position.coords.latitude;

const longitude = position.coords.longitude;

this.geocodingService.getAddress(latitude, longitude).subscribe(response => {

this.address = response.results[0].formatted_address;

});

}, error => {

console.log(‘Error: ‘, error);

});

}

}

This code imports the GeocodingService and sets up a locateMe() function that retrieves the user’s current location using the navigator.geolocation API. It then sends a request to the Google Maps Geocoding API using the GeocodingService, and updates the address variable with the formatted address from the response.

f. In the geocoding.service.ts file, add the following code:

import { Injectable } from ‘@angular/core’;

import { HttpClient } from ‘@angular/common/http’;

import { Observable } from ‘rxjs’;

@Injectable({

providedIn: ‘root’

})

export class GeocodingService {

private geocodingApiUrl = ‘https://maps.googleapis.com/maps/api/geocode/json';

constructor(private http: HttpClient) { }

getAddress(latitude: number, longitude: number): Observable<any> {

const url = `${this.geocodingApiUrl}?latlng=${latitude},${longitude}&key=<YOUR_API_KEY>`;

return this.http.get<any>(url);

}

}

This code creates a “GeocodingService” that sends requests to the Google Maps Geocoding API using the user’s latitude and longitude coordinates.

g. Replace <YOUR_API_KEY> in the geocoding.service.ts file with your own Google Maps API key.

h. In the app.module.ts file, add the following code:

import { NgModule } from ‘@angular/core’;

import { BrowserModule } from ‘@angular/platform-browser’;

import { HttpClientModule } from ‘@angular/common/http’;

import { AppComponent } from ‘./app.component’;

import { GeocodingService } from ‘./geocoding.service’;

@NgModule({

declarations: [

AppComponent

],

imports: [

BrowserModule,

HttpClientModule

],

providers: [GeocodingService],

bootstrap: [AppComponent]

})

export class AppModule { }

This code imports the HttpClientModule and the GeocodingService, and sets them up in the providers array.

i. Run the following command to start the development server:

ng serve –open

Now here to understand one point

  • The Google Cloud Console ( https://console.cloud.google.com/) should be accessed.

Note : Before using the API key, it is important to check if the Google Maps JavaScript API has been enabled in the project. To do this, navigate to the “APIs & Services” > “Library” menu item located in the left sidebar and search for “Google Maps JavaScript API.” If it is not enabled, click the “Enable” button to activate it.

Explanation of Code : To retrieve the user’s current position, the getCurrentPosition() method is used. This method takes two callbacks as parameters; the first callback is invoked when the position is successfully retrieved, and the second callback is invoked when an error occurs. Once the position is successfully retrieved, the latitude and longitude values are extracted from the coordinates object. To obtain the formatted address of the user’s current location, the “geocodingService” is utilized. Using the getAddress() method, the latitude and longitude are passed as parameters which in turn returns an observable that emits the response from the Google Maps Geocoding API.

The response from the observable is handled by making use of the subscribe() method. The response object contains an array of results, with each result representing a possible match for the given latitude and longitude. From the first result in the array, the formatted_address string is extracted and assigned to the address property of the component.

For this i am also attaching this project to my git library you can access and try to run with replacing your key that is available on “geocodingService ” File.


https://github.com/upadhyayneeraj90/LocateMe

1 comment:

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow