Hello friends, in this article, we will talk about how to get the user’s location with Xamarin. In almost every application, we make transactions with the location of the user. This is why this topic is very important. Before Xamarin.Essentials, we could do this with the Xam.Plugin.Geolocator package. Now we can do it much more easily without installing any additional packages. You can find the previous article here. You can find more information about Xamarin.Essential here.
The function that returns the location of the user needs to be asynchronous. Because in order to get the location of the user, it must first ask the user for permission. Then it will take action according to this permission. If the user allows and there is no hardware problem, the location will reach you, but we have to consider every scenario here. Many situations have to be managed.
With the following snippet, it throws PermissionException if the user does not grant location permission. If the device does not support the location or if there is a problem due to any hardware problem, it will fall into other catch blocks. You can show error messages or guide the user accordingly. The user did not give location permission and then when he tries to do a location-related action again, he has to go to the settings and open it himself from here. For this process, you can ask the user if he wants to go to the settings. After this notification, you can assign the user to the settings.
async void GetLocation() { try { var location = await Geolocation.GetLastKnownLocationAsync(); if (location != null) { Latitude = location.Latitude.ToString(); Longitude = location.Longitude.ToString(); } } catch (FeatureNotSupportedException ex) { Debug.WriteLine(ex.Message); } catch (FeatureNotEnabledException ex) { Debug.WriteLine(ex.Message); } catch (PermissionException ex) { Debug.WriteLine(ex.Message); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
If you have questions, you can reach us by sending an e-mail or comment. Good work.
Leave a Reply