Within my Ionic 3 app, I developed a function to retrieve a user's location based on their latitude and longitude coordinates. This function also verifies if the user has location settings enabled. If not, it prompts the user to switch on their location services by calling
this.diagnostic.switchToLocationSettings()
. Additionally, I implemented the this.diagnostic.registerLocationStateChangeHandler
method to confirm whether the user has indeed enabled location services after being prompted. Once all checks are passed, the function proceeds to fetch the geolocation and translate it into an address.
Below is the complete code snippet:
getMyLocation() {
this.geoOptions = {
enableHighAccuracy: false
}
const loadingMsg = this.loadingCtrl.create({
content: "Getting your location..."
})
loadingMsg.present();
this.diagnostic.isLocationEnabled().then(test => {
this.diagnostic.registerLocationStateChangeHandler((state)=>{
if((this.platform.is('ios')) && (state !== this.diagnostic.permissionStatus.GRANTED ||
state !== this.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE) ||
(this.platform.is('android')) && (state === this.diagnostic.locationMode.LOCATION_OFF )){
return Promise.reject("Please switch on your location");
}
})
if (!test) {
this.diagnostic.switchToLocationSettings()
}
return this.geolocation.getCurrentPosition(this.geoOptions)
},(err:any)=>{
loadingMsg.dismiss();
console.log("error : " + err);
}).then((pos: Geoposition) =>{
return this.nativeGeocoder.reverseGeocode(pos.coords.latitude, pos.coords.longitude);
},(err: PositionError)=>{
loadingMsg.dismiss();
console.log("error : " + err.message);
return Promise.reject(err.message);
}).then((result: NativeGeocoderReverseResult) =>{
this.currentAddress = result.locality+", "+result.countryName;
loadingMsg.dismiss();
},(err:any)=>{
console.log("error : " + err);
loadingMsg.dismiss();
return Promise.reject(err);
})
}
An issue I encountered was my inability to halt the promise chaining process if the user failed to enable location services after the prompt triggered by
this.diagnostic.switchToLocationSettings()
. I attempted to stop the chaining within the this.diagnostic.registerLocationStateChangeHandler
callback function without success. As a novice in using promise chaining techniques, any guidance on how to resolve this would be appreciated.