This is a library for declarative use of Geolocation API with Angular
npm install @ng-web-apis/geolocation
!npm bundle size

This is an Observable based abstraction over
Geolocation API to use with Angular
If you do not have @ng-web-apis/common:
``bash`
npm i @ng-web-apis/common
Now install the package:
`bash`
npm i @ng-web-apis/geolocation
WaGeolocationService is an Observable, that emits
Position object
Import service in your component:
`ts`
export class Example {
private readonly geolocation$ = inject(WaGeolocationService);
}
Now, to observe user position, you can subscribe to geolocation$:
`ts`
this.geolocation$.subscribe((position) => doSomethingWithPosition(position));
If you need to get position just once and stop observing user location, you can subscribe to geolocation$ and usetake(1) RxJS operator:
`ts`
geolocation$.pipe(take(1)).subscribe((position) => doSomethingWithPosition(position));
Or you can use async pipe to get position directly in template:
`html`
@if (geolocation$ | async; as position) { {{position.coords.latitude}} }
Service is cold, meaning if there are no active subscriptions, it doesn't track position.
The library also provides some tokens to simplify working with
Geolocation API:
- WA_GEOLOCATION_SUPPORT returns true if user's browser supports
Geolocation API
`ts`
export class Example {
private readonly geolocationSupport = inject(WA_GEOLOCATION_SUPPORT);
}
- You can provide PositionOptions through
WA_POSITION_OPTIONS token with optional properties named enableHighAccuracy, timeout and maximumAge. It uses{}
by default.
`ts`
bootstrapApplication(App, {
providers: [
{
provide: WA_POSITION_OPTIONS,
useValue: {enableHighAccuracy: true, timeout: 3000, maximumAge: 1000},
},
],
});
- navigator.geolocation can be injected through
WA_GEOLOCATION` token.
| 
| 
| 
| 
| 
|
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 9+ | 3.5+ | 5+ | 5+ | 3.2+ |
You can try online demo here
Other Web APIs for Angular by
@ng-web-apis