大家好我正在尝试从我的设备获取位置,这是我正在使用的代码:
public class Geolocation
{
private readonly LocationManager _locationManager;
public Geolocation()
{
_locationManager = Forms.Context.GetSystemService(Context.LocationService) as LocationManager;
}
public Task<double> GetLocation()
{
var provider = _locationManager.GetBestProvider(new Criteria() { Accuracy = Accuracy.Fine }, true);
var location = _locationManager.GetLastKnownLocation(provider);
if(location == null) return null;
var result = location.Latitude;
return result;
}
}
我从一本关于xamarin的书中得到了这个代码,我不明白的是为什么大部分时间我都没有从中得到结果,很少有人工作但我不知道为什么,希望你们帮助我并指导我,如果我错过了这里重要的东西,对于那些想知道我为什么不使用James Montemagno的Geolocator插件的人是因为我不能,它需要在我的VS中无法更新的东西。
答案 0 :(得分:1)
尝试通过依赖服务进行协调。阅读xamrin文档 Get Current Device Location github get_current_device_location
中有一个示例项目仍然希望它在xamarin.forms中实现,然后看到此视频link
答案 1 :(得分:1)
{{1}}
尽管准确度较低,但这样可以更快地为您提供位置。
Here是如何检索位置的综合示例。
答案 2 :(得分:1)
以下是如何使用Xamarin.Forms项目中的GeoLocator插件。
此代码片段取自使用带有Xamarin.Forms和MVVM架构的GeoLocator插件的示例Xamarin.Forms应用程序:
https://github.com/brminnick/GeolocatorSample
public class Geolocation
{
string _latLongText, _latLongAccuracyText, _altitudeText, _altitudeAccuracyText;
public Geolocation()
{
StartListeningForGeoloactionUpdates.GetAwaiter().GetResult();
}
public string LatLongText
{
get => _latLongText;
set => _latLongText = value;
}
public string LatLongAccuracyText
{
get => _latLongAccuracyText;
set => _latLongAccuracyText = value;
}
public string AltitudeText
{
get => _altitudeText;
set => _altitudeText = value;
}
public string AltitudeAccuracyText
{
get => _altitudeAccuracyText;
set => _altitudeAccuracyText = value;
}
Task StartListeningForGeoloactionUpdates()
{
bool isGeolocationAvailable = CrossGeolocator.IsSupported
&& CrossGeolocator.Current.IsGeolocationAvailable
&& CrossGeolocator.Current.IsGeolocationEnabled;
if (isGeolocationAvailable)
{
CrossGeolocator.Current.PositionChanged += HandlePositionChanged;
return CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(1), 10);
}
LatLongText = "Geolocation Unavailable";
return Task.CompletedTask;
}
void HandlePositionChanged(object sender, PositionEventArgs e)
{
AltitudeAccuracyText = $"{ConvertDoubleToString(e.Position.AltitudeAccuracy, 0)}m";
AltitudeText = $"{ConvertDoubleToString(e.Position.Altitude, 2)}m";
LatLongAccuracyText = $"{ConvertDoubleToString(e.Position.Accuracy, 0)}m";
LatLongText = $"{ConvertDoubleToString(e.Position.Latitude, 2)}, {ConvertDoubleToString(e.Position.Longitude, 2)}";
string ConvertDoubleToString(double number, int decimalPlaces) => number.ToString($"F{decimalPlaces}");
}
}