Forum Xamarin.Android

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to get current location?

I tried to get my device's current latitude, longitude values like the same way in here https://developer.xamarin.com/recipes/android/os_device_resources/gps/get_current_device_location/ but current location returned null and I could not get my device's location. I tired also in emulator and device.

How can I get the current latitude longitude values of my device?

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    Have you set permission in manifest?

  • BasakSeritBasakSerit USMember

    Yes, I set permissions for AccessFineLocation, AccessCoarseLocation and Internet.

  • I think you are testing it in simulator, If so Try it in a real device

  • cwphillicwphilli USMember ✭✭✭

    Take a look at my code below.

    private LocationManager _locationManager;
    private string _locationProvider;
    
    // .....
    
    #region GPS
    
        private void InitializeLocationManager()
        {
            _locationManager = (LocationManager)GetSystemService(LocationService);
            var criteriaForLocationService = new Criteria
            {
                Accuracy = Accuracy.Fine
            };
            var acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
    
            _locationProvider = acceptableLocationProviders.Any() ? acceptableLocationProviders.First() : string.Empty;
            Log.Debug(Tag, "Using " + _locationProvider + ".");
        }
    
        public void SubscribeToNotificationUpdates()
        {
            if (_locationManager.IsProviderEnabled(LocationManager.GpsProvider))
                _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
            else
            {
    #if DEBUG
                if (!App.ShownGpsPrompt)
                    BuildAlertMessageNoGps();
    #endif
            }
        }
    
        public void UnSubscribeToNotificationUpdates()
        {
            _locationManager.RemoveUpdates(this);
        }
    
        public async Task<Address> ReverseGeocodeCurrentLocation()
        {
            try
            {
                var geocoder = new Geocoder(this);
                var addressList = await geocoder.GetFromLocationAsync(Location.Latitude, Location.Longitude, 10);
                var address = addressList.FirstOrDefault();
                return address;
            }
            catch (Exception ex)
            {
                BusinessApp.Instance.Logger(ex.Message, ex.StackTrace);
            }
            return null;
        }
    
        private void BuildAlertMessageNoGps()
        {
            var builder = new AlertDialog.Builder(this);
            builder.SetMessage("Your GPS seems to be disabled, do you want to enable it?")
                .SetCancelable(false)
                .SetPositiveButton("Yes", (sender, e) =>
                {
                    StartActivity(new Intent(Settings.ActionLocationSourceSettings));
                })
                .SetNegativeButton("No", (sender, e) =>
                {
                    (sender as AlertDialog)?.Cancel();
                });
            var alert = builder.Create();
            alert.Show();
            App.ShownGpsPrompt = true;
        }
    
        #endregion
    

    Usage:

                // get GPS coordinates
                var address = await ReverseGeocodeCurrentLocation();
                if (address != null)
                {
                    var locationString =
                        $"{nameof(address.Locality)} : {address.Locality}; {nameof(address.SubLocality)} : {address.SubLocality}; {nameof(address.Premises)} : {address.Premises}; {nameof(address.Thoroughfare)} : {address.Thoroughfare}; {nameof(address.PostalCode)} : {address.PostalCode};";
                    // TODO: utilize address fields if available?
                    Console.WriteLine(locationString);
                }
                double? latitude = null;
                double? longitude = null;
                List<double?> point = null;
                if (Location != null)
                {
                    latitude = Location.Latitude;
                    longitude = Location.Longitude;
                    point = new List<double?>() { latitude, longitude };
                    Console.WriteLine($"{nameof(latitude)} : {latitude}, {nameof(longitude)} : {longitude}");
                }
    
Sign In or Register to comment.