geolocation
geolocation copied to clipboard
An Observable based abstraction to use Geolocation API with Angular
Geolocation API for Angular
Part of
Web APIs for Angular
This is an Observable based abstraction over Geolocation API to use with Angular
Install
If you do not have @ng-web-apis/common:
npm i @ng-web-apis/common
Now install the package:
npm i @ng-web-apis/geolocation
How to use
GeolocationService
GeolocationService is an Observable, that emits Position object
Import service in your component:
import {GeolocationService} from '@ng-web-apis/geolocation';
...
constructor(private readonly geolocation$: GeolocationService) {}
Now, to observe user position, you can subscribe to geolocation$:
geolocation$.subscribe(position => doSomethingWithPosition(position));
If you need to get position just once and stop observing user location, you can subscribe to geolocation$ and use take(1) RxJs operator:
geolocation$.pipe(take(1)).subscribe(position => doSomethingWithPosition(position));
Or you can use async pipe to get position directly in template:
<div *ngIf="geolocation$ | async as position">
<span>{{position.coords.latitude}}</span>
</div>
Service is cold, meaning if there are no active subscriptions, it doesn't track position.
Tokens
The library also provides some tokens to simplify working with Geolocation API:
GEOLOCATION_SUPPORTreturnstrueif user's browser supports Geolocation API
export class YourComponent {
constructor(
@Inject(GEOLOCATION_SUPPORT) private readonly geolocationSupport: boolean
) {}
...
- You can provide PositionOptions
through
POSITION_OPTIONStoken with optional properties namedenableHighAccuracy,timeoutandmaximumAge. It uses{}by default.
@NgModule({
...
providers: [
{
provide: POSITION_OPTIONS,
useValue: {enableHighAccuracy: true, timeout: 3000, maximumAge: 1000},
},
],
})
export class AppModule {}
- navigator.geolocation
can be injected through
GEOLOCATIONtoken.
Browser support
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|
| 9+ | 3.5+ | 5+ | 5+ | 3.2+ |
Demo
You can try online demo here
See also
Other Web APIs for Angular by @ng-web-apis
Open-source
Do you also want to open-source something, but hate the collateral work? Check out this Angular Open-source Library Starter we’ve created for our projects. It got you covered on continuous integration, pre-commit checks, linting, versioning + changelog, code coverage and all that jazz.




