如何解决我想使用 xamarin.forms 获取每一帧的当前位置
当我调用函数时,我有一次我的位置,但我想在应用程序中的每一帧都获得我的位置。我的意思是当我用手机移动时,位置会改变。我试图做 while(true) 但它没有用。 当我在主函数中调用它时。它将运行一次。这是我的功能。
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;
}
解决方法
使用 GeoLocator 插件
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。