I have placed the geolocation call in a service which I want to use in different areas of the application. However, undefined is being returned. How do I return the value properly so that it can be retrieved?
Service code
getUserPosition() {
this.geolocation.getCurrentPosition().then((position) => {
this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.currentLat = position.coords.latitude;
this.currentLng = position.coords.longitude;
return this.latLng;
}, (err) => {
console.log('There was an error');
});
}
Call this function from the service
async ngOnInit() {
// Since ngOnInit() is executed before `deviceready` event,
// you have to wait the event.
await this.platform.ready();
await this.loadMap();
this.val = await this.location.getUserPosition();
console.log("I should be here val "+ this.val);
}
Returning the details from the function
async getUserPosition() {
await this.geolocation.getCurrentPosition().then((position) => {
this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.currentLat = position.coords.latitude;
this.currentLng = position.coords.longitude;
this.locationData = [this.latLng, this.currentLat, this.currentLng];
}, (err) => {
console.log('There was an error' + err.message);
});
// return all the details returned from the location
return this.locationData;
}
Using the details returned
this.geolocationData = await this.location.getUserPosition();
this.latLng = this.geolocationData[0];
this.currentLat = this.geolocationData[1];
this.currentLng = this.geolocationData[2];