我正在使用Xamarin Forms创建一个跟踪用户位置的应用。我目前正在尝试使用this Geolocator
插件来跟踪用户的位置。我已经按照插件教程中的步骤进行了操作,但我的位置目前还没有刷新。
这是我的代码:
public WhosOnFarm ()
{
InitializeComponent ();
locator = CrossGeolocator.Current;
locator.PositionChanged += (sender, e) => {
DisplayAlert("Success", "Your position has changed!", "OK");
var position = e.Position;
longitudeLabel.Text = "Longitude: "+position.Longitude.ToString() + " Latitude: " + position.Latitude.ToString();
};
}
在教程中,它没有指定locator
的类型,所以我假设它需要的数据CrossGeolocator.Current;
我错过了什么?
答案 0 :(得分:0)
如果没有项目设置,有点难以回答你的问题。位置插件(例如GeoLocation)需要在项目中设置一些属性(权限)。你加了那些吗?你在哪个平台上使用它?在什么设备或模拟器上测试它?
答案 1 :(得分:0)
我已经实现了相同的库以下是我的代码 完美地在Android和iOS上工作
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
CrossGeolocator.Current.AllowsBackgroundUpdates = true;
CrossGeolocator.Current.DesiredAccuracy = 50;
CrossGeolocator.Current.PositionChanged += Current_PositionChanged;
}
protected override void OnAppearing()
{
base.OnAppearing();
updateLocation();
}
private async void updateLocation()
{
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
locator.AllowsBackgroundUpdates = true;
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
if (position == null)
{
lblData.Text = "null gps :(";
return;
}
lblData.Text = string.Format("\nTime: {0} \nLat: {1} \nLong: {2} \n Altitude: {3} \nAltitude Accuracy: {4} \nAccuracy: {5} \n Heading: {6} \n Speed: {7}",
position.Timestamp, position.Latitude, position.Longitude,
position.Altitude, position.AltitudeAccuracy, position.Accuracy, position.Heading, position.Speed);
mapVar.MoveToRegion(
MapSpan.FromCenterAndRadius(
new Position(position.Latitude,position.Longitude), Distance.FromKilometers(1)));
await CrossGeolocator.Current.StartListeningAsync(1, 2, true);
}
catch (Exception)
{
}
}
private void Current_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e)
{
if (e.Position != null)
{
Device.BeginInvokeOnMainThread(() => {
var position = e.Position;
lblData.Text = string.Format("\n\nTime: {0} \nLat: {1} \nLong: {2} \n Altitude: {3} \nAltitude Accuracy: {4} \nAccuracy: {5} \n Heading: {6} \n Speed: {7}",
position.Timestamp, position.Latitude, position.Longitude,
position.Altitude, position.AltitudeAccuracy, position.Accuracy, position.Heading, position.Speed);
mapVar.Pins.Clear();
mapVar.Pins.Add(new Xamarin.Forms.Maps.Pin
{
Position = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude),
Type = Xamarin.Forms.Maps.PinType.Place,
Label = "My Location"
});
mapVar.MoveToRegion(
MapSpan.FromCenterAndRadius(
new Position(position.Latitude, position.Longitude), Distance.FromKilometers(1)));
});
}
}
}