Frank Guerra
Frank Guerra

Reputation: 49

getting location in xamarin forms

I am trying to get the location from my device. This is the code:

public class Geolocation
{        
    private readonly LocationManager _locationManager;

    public Geolocation()
    {
        _locationManager = Forms.Context.GetSystemService(Context.LocationService) as LocationManager;
    }

    public Task<double> GetLocation()
    {

        var provider = _locationManager.GetBestProvider(new Criteria() { Accuracy = Accuracy.Fine }, true);
        var location = _locationManager.GetLastKnownLocation(provider);

        if(location == null) return null;

        var result = location.Latitude;

        return result;
    }
}

I got this code from a book about xamarin. What I don't understand, why the majority of time I don't get a result from that? Few times it works, but I don't know why. For those wondering why am i not using James Montemagno's Geolocator plugin is because I can't. It requires something that can't be updated in my VS.

Upvotes: 2

Views: 2898

Answers (3)

Brandon Minnick
Brandon Minnick

Reputation: 15410

Below is how to use the GeoLocator plugin from a Xamarin.Forms project.

This code snippet is taken from sample Xamarin.Forms app that uses the GeoLocator plugin with Xamarin.Forms and an MVVM architecture:

https://github.com/brminnick/GeolocatorSample

public class Geolocation
{ 
    string _latLongText, _latLongAccuracyText, _altitudeText, _altitudeAccuracyText;

    public Geolocation()
    {
        StartListeningForGeoloactionUpdates.GetAwaiter().GetResult();
    }

    public string LatLongText
    {
        get => _latLongText;
        set => _latLongText = value;
    }

    public string LatLongAccuracyText
    {
        get => _latLongAccuracyText;
        set => _latLongAccuracyText = value;
    }

    public string AltitudeText
    {
        get => _altitudeText;
        set => _altitudeText = value;
    }

    public string AltitudeAccuracyText
    {
        get => _altitudeAccuracyText;
        set => _altitudeAccuracyText = value;
    }

    Task StartListeningForGeoloactionUpdates()
    {
        bool isGeolocationAvailable = CrossGeolocator.IsSupported
                                    && CrossGeolocator.Current.IsGeolocationAvailable
                                    && CrossGeolocator.Current.IsGeolocationEnabled;

        if (isGeolocationAvailable)
        {
            CrossGeolocator.Current.PositionChanged += HandlePositionChanged;
            return CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(1), 10);
        }

        LatLongText = "Geolocation Unavailable";
        return Task.CompletedTask;
    }

    void HandlePositionChanged(object sender, PositionEventArgs e)
    {
        AltitudeAccuracyText = $"{ConvertDoubleToString(e.Position.AltitudeAccuracy, 0)}m";
        AltitudeText = $"{ConvertDoubleToString(e.Position.Altitude, 2)}m";
        LatLongAccuracyText = $"{ConvertDoubleToString(e.Position.Accuracy, 0)}m";
        LatLongText = $"{ConvertDoubleToString(e.Position.Latitude, 2)}, {ConvertDoubleToString(e.Position.Longitude, 2)}";

        string ConvertDoubleToString(double number, int decimalPlaces) => number.ToString($"F{decimalPlaces}");
    }
}

Upvotes: 1

Hichame Yessou
Hichame Yessou

Reputation: 2718

_locationManager.GetBestProvider(new Criteria() { Accuracy = Accuracy.Coarse}, true);

This would give you the location faster, despite a lower accuracy of course.
Here is a comprehensive example of how the location should be retrieved.

Upvotes: 1

Supun Liyanaarachchi
Supun Liyanaarachchi

Reputation: 549

try to get coordination by dependency service. Read xamrin documentation Get Current Device Location There is a sample project in github get_current_device_location

and still you want it to implement in xamarin.forms then see this video link

Upvotes: 1

Related Questions