
Whilst building a weather app I needed access to the browsers location information in order to display relevant weather information and I thought it might be of use if I posted the method I used.
Geolocation.getCurrentPosition()
The Geolocation.getCurrentPosition() method can be used to get the current location. It accepts one mandatory parameter which is a callback function along with several optional parameters. When invoked this method will bring up a browser notification so that the user can allow or block the request for location information.
To use this method in my Angular app I wrapped the call to Geolocation.getCurrentPosition inside an Observable method called getPosition.
getPosition(): Observable<any> {
return Observable.create(observer => {
window.navigator.geolocation.getCurrentPosition(position => {
observer.next(position);
observer.complete();
},
error => observer.error(error));
});
}
This method will notify its subscribers when the user agrees to allow the application access to the browsers location data.
With getPosition in place, I placed a call to subscribe to the observable from an Angular components ngOnInit lifecycle hook.
...
this.getPosition().subscribe(pos => {
console.log(pos);
console.log(pos.coords.latitude);
console.log(pos.coords.longitude);
});
...
I have purposefully left in the evolving calls to console.log to give an indication of how you can gain a better understanding of what the pos object contains.
This stuff is hard
The problem with a blog post is that it can look all too easy to showcase a solution and not the amount of wrong turns and dead ends that were taken. I didn’t want to end this post abruptly with a da dah and here is the solution. Instead I wanted to say something about how I arrived at the solution I have just described.
I started off trying to call Geolocation.getCurrentPosition and implement my own callback function but soon found myself in a world of trying to set “this” to the right context. I then went down the route of using a Promise which worked but didn’t feel right especially after reading the many posts discussing Promise v Observable so I finally ended up using an Observable. Even now I’m not 100% happy with the solution because I am using the any type. Please get in touch if you know how I could have used a more appropriate type!
Acknowledgements
To everyone that has written a blog, asked or answered a Stack Overflow question, posted a YouTube video, delivered a Plurasight course on Observables. Thank you it is really appreciated.