This articles explains how your xamarin forms mobile app can ask user to enable location services, obtain location permission and coordinates such as latitude, longitude and altitude on Android and iOS devices. It also has few other things I have learned while working with location in Xamarin Forms.
I have created a sample application to make it easier to understand the steps required before your xamarin app can have access to user's location. This app uses platform specific code and Xamarin Essentials to get geolocation.
Step 1: Configuration
Before getting the location information, its important to configure the project.
Android
Android needs to know what type of permission the app could request from user.
Depending upon your requirements, you may need to add few of these permissions
in your AndroidManifest.xml
file.
iOS
iOS shows the following string when requesting location permission from app user.
Make sure you replace it with the your reason for getting location information from user
and add these in your info.plist
file.
Step 2: Location Services
Second step to get location information is to make sure location services are enabled on user's mobile device. The following platform specific code will tell you whether you need to request user to enable them.
Android
iOS
If the location services are not enabled then you would need to request user to enable them. Unfortunately there is no easy way to prompt the user to enable location services programmatically but instead you can programmatically open device location settings page where user can toggle the switch to enable them, however this only works on Android.
Android
Step 3: Location Permission
Your application need to request the user to grant it permission to access the location service. You could write that logic manually in Android and iOS code base but its easier to use Xamarin Essentials from Xamarin team because the app now can check and request for location permission from shared code.
The following code returns current permission status
The following code requests the permission and returns status
If the user denied the location permission request, you can try to request it again but sometimes operating system does not prompt the user to grant permission. In that case, the only way to request the user to grant permission is to redirect them to app settings page. Fortunately, Xamarin Essentials provide a way to do that.
Step 4: Location Information
Once your application has access to location services and appropriate location permission, then last step is to actually get location Information. The following piece of code will return location information.
Thank You!
Thanks for reading. The source code for the sample application is available at github.