Jignesh zala
1 min readSep 30, 2022

In this article, we will see how to get the user’s current location in Angular 14+.

Generate location service

ng g service services/location/location

It will create location service inside services folder

Now add below code in it

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root',
})
export class LocationService {
constructor() {}

getCurrentLocation() {
return new Promise((resolve, reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
if (position) {
console.log(
'Latitude: ' +
position.coords.latitude +
'Longitude: ' +
position.coords.longitude
);
let lat = position.coords.latitude;
let lng = position.coords.longitude;

const location = {
lat,
lng,
};
resolve(location);
}
},
(error) => console.log(error)
);
} else {
reject('Geolocation is not supported by this browser.');
}
});
}
}

Original Article Published on: https://tutscoder.com/post/get-current-location-angular

Now use this location service in app.component.ts file as below:

const position: any = await this.locationService.getCurrentLocation();
console.log(position);

You will get the current latitude and longitude on the console.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jignesh zala
Jignesh zala

Written by Jignesh zala

MEAN Stack Developer and founder of TutsCoder.com, sharing tech insights, tutorials, and resources on Angular, Node.js, JavaScript, and more for developers.

No responses yet

Write a response