There is a page where 3 different locations information is listed.
These 3 locations are displayed on page through for loop. The requirement is to get user's current position and calculate distance between user's current location and the 3 locations and display distances for each in miles.
I have written a subscribe() method to get currentPosition() in ngOnInit() function like below:
ngOnInit() {
this.getLoc().subscribe(location => {
console.log(location);
});
}
getLoc(): Observable<{ coords: { latitude: number, longitude: number } }> {
return new Observable(observer => {
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
(pos) => {
observer.next(pos);
observer.complete();
},
(error) => {
switch (error.code) {
case 1:
observer.error(GEOLOCATION_ERRORS.errors.location.permissionDenied);
break;
case 2:
observer.error(GEOLOCATION_ERRORS.errors.location.positionUnavailable);
break;
case 3:
observer.error(GEOLOCATION_ERRORS.errors.location.timeout);
break;
}
},
{ maximumAge: 120000 }
);
} else {
observer.error(GEOLOCATION_ERRORS.errors.location.unsupportedBrowser);
}
});
}
Here, code goes inside ngOnInit() for 3 times since there are 3 locations listed on page.
Further more, code also goes inside if condition of getLoc() function.
However, it takes time to get current position from getCurrentPosition() and as a result, by the time it gets position, the for loop finishes first two locations and considers only last location and calculate distance between currentpostion and last location
My question is how to make angular wait to get currentposition() before proceeding for the execution of next code? Also, this issue occurs only in Firefox. Other browsers such as Chrome and Edge are behaving as expected.