Search code examples
androidxamarin.formsxamarin.androidgeolocationandroid-gps

Xamarin forms get current location take more time


I have xamarin forms app and have functionality to capture current user location and i using CrossGeolocator PLugin
and these part of code for get location:

   locator = CrossGeolocator.Current;
   var position = await locator.GetPositionAsync();
   order.@long = position.Longitude;
   order.lat = position.Latitude;

its return location but some times take more time to return current location is there any solution to decrease location capture time. Thanks


Solution

  • If you want to speed up the process - use Xamarin.Essentials. Xamarin.Essentials provides an excellent way to get the users location which is a faster alternative than using the Geolocator Plugin. Not only that - Xamarin.Essentials is tested well and is backed by Microsoft itself.

    First of all paste the following code in your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location" android:required="false" />
    <uses-feature android:name="android.hardware.location.gps" android:required="false" />
    <uses-feature android:name="android.hardware.location.network" android:required="false" />
    

    Here is an example of getting the user's latitude and longitude - you can adapt the code below to your project:

    var position = await Xamarin.Essentials.Geolocation.GetLocationAsync();
    
                double latitude = position.Latitude;
    
                double longitude = position.Longitude;
    

    For more info regarding GeoLocation go to https://learn.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=android.

    You should notice a significant difference in speed when you use Xamarin.Essentials.