Get Current Location Using Angular and Google Maps API - Step-by-Step Tutorial
Hi Everyone, hope you all are doing well.
- 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.
- What the Google Maps Geocoding API is and how it can be used to convert latitude and longitude coordinates into human-readable addresses: we can introduce the Google Maps Geocoding API and explain how it could used to convert geographical coordinates into addresses. We can describe the various parameters and options available for the API, such as address components, location types, and viewport biasing. We can also mention some of the limitations and restrictions of the API, such as usage quotas, billing, and caching policies.
- Angular framework and how it can be used to build web applications: Angular can be used to create dynamic web applications using components, templates, and services. We can also take advantage of various features offered by Angular, such as modularity, reusability, and testability.
- Create a new Angular project and install the required dependencies to use the Google Maps Geocoding API. We can use the Angular CLI to create a new project, generate components and services, and install packages using npm. We can explain how to configure the API key for the Geocoding API and secure our application by setting up CORS policies. Let’s get started!
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.
- A new project can be created by clicking the “New Project” button in the “Select a Project” dropdown located at the top of the screen.
- A name should be given to the project and the “Create” button should be clicked.
- Once the project is created, it can be selected from the “Select a Project” dropdown.
- The “APIs & Services” menu item can be clicked in the left sidebar.
- The “Credentials” submenu item can be clicked.
- The “Create Credentials” dropdown can be clicked and “API key” should be selected.
- The generated API key can be copied and used in the code.
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