Search code examples
c#xamarinxamarin.formsxamarin.android

i want to get my current position every frame with xamarin.forms


I have my position once when i call the function but i want to get my position every frame in the app.I mean when i move with the phone, the position change. I have tried to do while(true) but it didn't work. when i call it in the main function. it will be run one time. and this is my function.

 public async Task<Location> GetCurrentLocation()
    {
       var p = new Location();
        try
        {
            var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));

            cts = new CancellationTokenSource();

            var location = await Geolocation.GetLocationAsync(request, cts.Token);

             if (location != null)
             {
                 Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");

                 map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(location.Latitude, location.Longitude), Distance.FromMeters(100)));

            }
            return location;

        }
        catch (FeatureNotSupportedException fnsEx)
        {
            await DisplayAlert("Faild", fnsEx.Message, "OK");
        }
        catch (PermissionException pEx)
        {
            await DisplayAlert("Faild", pEx.Message, "OK");
        }
        catch (Exception ex)
        {
            await DisplayAlert("Faild", ex.Message, "OK");
        }
        return p;
    }

Solution

  • use the GeoLocator plugin

    async Task StartListening()
    {
        if(CrossGeolocator.Current.IsListening)
            return;
        
      await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 10, true);
    
      CrossGeolocator.Current.PositionChanged += PositionChanged;
      CrossGeolocator.Current.PositionError += PositionError;
    }
    
    private void PositionChanged(object sender, PositionEventArgs e)
    {
      
      //If updating the UI, ensure you invoke on main thread
      var position = e.Position;
      var output = "Full: Lat: " + position.Latitude + " Long: " + position.Longitude;
      output += "\n" + $"Time: {position.Timestamp}";
      output += "\n" + $"Heading: {position.Heading}";
      output += "\n" + $"Speed: {position.Speed}";
      output += "\n" + $"Accuracy: {position.Accuracy}";
      output += "\n" + $"Altitude: {position.Altitude}";
      output += "\n" + $"Altitude Accuracy: {position.AltitudeAccuracy}";
      Debug.WriteLine(output);
    } 
    
    private void PositionError(object sender, PositionErrorEventArgs e)
    {
      Debug.WriteLine(e.Error);
      //Handle event here for errors
    } 
    
    async Task StopListening()
    {
        if(!CrossGeolocator.Current.IsListening)
            return;
        
      await CrossGeolocator.Current.StopListening);
    
      CrossGeolocator.Current.PositionChanged -= PositionChanged;
      CrossGeolocator.Current.PositionError -= PositionError;
    }