Xamarin - Access Android Mobile Current GPS Location

Today we discuss how to access current location latitude and longitude of Android mobile using Xamarin.Mobile.dll component.

Open Microsoft Visual Studio 2017 => create new application and name it is AccessGPSLocation. Add reference to Xamarin.Mobile.dll component.

Here we are calling GetPositionAsync() method from Geolocator class to get the latitude and longitude as shown below. 

using Android.App;

using Android.Widget;

using Android.OS;

using Xamarin.Geolocation;

using System.Threading.Tasks;

 

namespace AccessGPSLocation

{

    [Activity(Label = "AccessGPSLocation", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity

    {

        public class Location

        {

            public double Latitude { get; set; }

            public double Longitude { get; set; }

        }


        private const int Timeout = 3000; private Geolocator _geolocator;

        public async Task<Location>GetCurrentLocation()

        {

            if (_geolocator == null)

                _geolocator = new Geolocator(Application.Context);

 

            var location = await _geolocator.GetPositionAsync(Timeout);

            return new Location { Latitude = location.Latitude, Longitude = location.Longitude, };

        }

 

        protected override void OnCreate(Bundle bundle)

        {

            base.OnCreate(bundle);

 

            // Set our view from the "main" layout resource

            SetContentView(Resource.Layout.Main);

 

            var location = GetCurrentLocation().GetAwaiter();

 

            TextView txtLatitude = FindViewById<TextView>(Resource.Id.txtLatitude);

            TextView txtLongitude = FindViewById<TextView>(Resource.Id.txtLongitude);

 

            txtLatitude.Text = location.GetResult().Latitude.ToString();

            txtLongitude.Text = location.GetResult().Longitude.ToString();

        }      

    }

} 

As shown above we are calling the GetPositionAsync() method to get the location details. To access the location from mobile, we need to edit the Android Manifest file. To do that, right-click on project and select properties; check AccessCoarseLocation and AccessFineLocation under Required permissions section. 

Connect any Android mobile and build the application. The new application AccessGPSLocation displays longitude and latitude on two text areas.

 

                                                                                                       AccessGPSLocation.zip