实时更新GeoLocaiton

时间:2019-10-24 16:34:30

标签: xamarin xamarin.forms

我正在为自己的学习构建一个小型正在运行的应用程序,我正在尝试使用xamrain Essentials地理位置来获取GPS位置,以使其适合人工输入,当它们输入时将其存储在列表中更新,但我可以订阅他们的活动,它会告诉我位置何时更改,因为在大多数正在运行的应用程序中,用户无需单击按钮。

private async void BtnStart_OnClicked(object sender, EventArgs e)
{
    var location = await Geolocation.GetLastKnownLocationAsync();
    if (location != null)
    {
      Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
    }

        lbllong.Text = location.Longitude.ToString();

        lbllat.Text = location.Latitude.ToString();
        Location StartLocation = new Location(location.Latitude,location.Longitude);
        Location endLocation = new Location(37.783333, -122.416667);

        double miles = Location.CalculateDistance(StartLocation, endLocation, DistanceUnits.Miles);

}

我希望它能够每隔几英尺更新一次,但是我看不到任何可以挂入的事件。

1 个答案:

答案 0 :(得分:1)

  

我希望它能够每隔几英尺更新一次,但是我看不到任何可以挂入的事件。

如果您想在距离或超时时更新位置,如Jason所说,可以通过安装nuget软件包来使用 Xam.Plugin.Geolocator

您可以实现此方法来监视时间和距离:

Task<bool> StartListeningAsync(TimeSpan minimumTime, double minimumDistance, bool includeHeading = false, ListenerSettings listenerSettings = null);

并订阅此事件以获取当前位置:

CrossGeolocator.Current.PositionChanged += CrossGeolocator_Current_PositionChanged;

您可以通过Jason的第一个链接看到整个示例,我提供了所需的代码:

bool tracking;

    public ObservableCollection<Position> Positions { get; } = new ObservableCollection<Position>();

    public HomePage()
    {
        InitializeComponent();
        ListViewPositions.ItemsSource = Positions;
    }

private async void ButtonTrack_Clicked(object sender, EventArgs e)
    {
        try
        {
            var hasPermission = await Utils.CheckPermissions(Permission.Location);
            if (!hasPermission)
                return;

            if (tracking)
            {
                CrossGeolocator.Current.PositionChanged -= CrossGeolocator_Current_PositionChanged;
                CrossGeolocator.Current.PositionError -= CrossGeolocator_Current_PositionError;
            }
            else
            {
                CrossGeolocator.Current.PositionChanged += CrossGeolocator_Current_PositionChanged;
                CrossGeolocator.Current.PositionError += CrossGeolocator_Current_PositionError;
            }

            if (CrossGeolocator.Current.IsListening)
            {
                await CrossGeolocator.Current.StopListeningAsync();
                labelGPSTrack.Text = "Stopped tracking";
                ButtonTrack.Text = "Start Tracking";
                tracking = false;
                count = 0;
            }
            else
            {
                Positions.Clear();
                if (await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(TrackTimeout.Value), TrackDistance.Value,
                    TrackIncludeHeading.IsToggled, new ListenerSettings
                    {
                        ActivityType = (ActivityType)ActivityTypePicker.SelectedIndex,
                        AllowBackgroundUpdates = AllowBackgroundUpdates.IsToggled,
                        DeferLocationUpdates = DeferUpdates.IsToggled,
                        DeferralDistanceMeters = DeferalDistance.Value,
                        DeferralTime = TimeSpan.FromSeconds(DeferalTIme.Value),
                        ListenForSignificantChanges = ListenForSig.IsToggled,
                        PauseLocationUpdatesAutomatically = PauseLocation.IsToggled
                    }))
                {
                    labelGPSTrack.Text = "Started tracking";
                    ButtonTrack.Text = "Stop Tracking";
                    tracking = true;
                }
            }
        }
        catch (Exception ex)
        {
            await DisplayAlert("Uh oh", "Something went wrong, but don't worry we captured for analysis! Thanks.", "OK");
        }
    }




void CrossGeolocator_Current_PositionError(object sender, PositionErrorEventArgs e)
{

    labelGPSTrack.Text = "Location error: " + e.Error.ToString();
}

void CrossGeolocator_Current_PositionChanged(object sender, PositionEventArgs e)
{

    Device.BeginInvokeOnMainThread(() =>
    {
        var position = e.Position;
        Positions.Add(position);
        count++;
        LabelCount.Text = $"{count} updates";
        labelGPSTrack.Text = string.Format("Time: {0} \nLat: {1} \nLong: {2} \nAltitude: {3} \nAltitude Accuracy: {4} \nAccuracy: {5} \nHeading: {6} \nSpeed: {7}",
            position.Timestamp, position.Latitude, position.Longitude,
            position.Altitude, position.AltitudeAccuracy, position.Accuracy, position.Heading, position.Speed);

    });
}

https://github.com/jamesmontemagno/GeolocatorPlugin/blob/master/samples/GeolocatorSample/GeolocatorSample/HomePage.xaml.cs