检查权限
在开始跟踪之前,您必须检查以确保您在所有平台上都拥有位置权限。我建议使用 Permissions Plugin 以确保您拥有权限。
开始跟踪
/// <summary>
/// Start listening for changes
/// </summary>
/// <param name="minimumTime">Time</param>
/// <param name="minimumDistance">Distance</param>
/// <param name="includeHeading">Include heading or not</param>
/// <param name="listenerSettings">Optional settings (iOS only)</param>
Task<bool> StartListeningAsync(TimeSpan minimumTime, double minimumDistance, bool includeHeading = false, ListenerSettings listenerSettings = null)
UWP 注意:地理定位器的工作方式必须设置 minTime 或 minDistance。设置两者意味着 minDistance 将优先于两者。您可以在 Windows 博客上阅读更多内容。
async Task StartListening()
{
if(CrossGeolocator.Current.IsListening)
return;
///This logic will run on the background automatically on iOS, however for Android and UWP you must put logic in background services. Else if your app is killed the location updates will be killed.
await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 10, true, new Plugin.Geolocator.Abstractions.ListenerSettings
{
ActivityType = Plugin.Geolocator.Abstractions.ActivityType.AutomotiveNavigation,
AllowBackgroundUpdates = true,
DeferLocationUpdates = true,
DeferralDistanceMeters = 1,
DeferralTime = TimeSpan.FromSeconds(1),
ListenForSignificantChanges = true,
PauseLocationUpdatesAutomatically = false
});
CrossGeolocator.Current.PositionChanged += Current_PositionChanged;
}
private void Current_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e)
{
Device.BeginInvokeOnMainThread(() =>
{
var test = e.Position;
listenLabel.Text = "Full: Lat: " + test.Latitude.ToString() + " Long: " + test.Longitude.ToString();
listenLabel.Text += "\n" + $"Time: {test.Timestamp.ToString()}";
listenLabel.Text += "\n" + $"Heading: {test.Heading.ToString()}";
listenLabel.Text += "\n" + $"Speed: {test.Speed.ToString()}";
listenLabel.Text += "\n" + $"Accuracy: {test.Accuracy.ToString()}";
listenLabel.Text += "\n" + $"Altitude: {test.Altitude.ToString()}";
listenLabel.Text += "\n" + $"AltitudeAccuracy: {test.AltitudeAccuracy.ToString()}";
});
}
欲了解更多信息,请使用以下链接
https://github.com/jamesmontemagno/GeolocatorPlugin