[Xamarin]如何取得使用者的地理位置
android專案的設定:
在androd專案底下的 \Properties\AssemblyInfo.cs加入下列內容
//加入讀取使用者位置的功能
[assembly: UsesPermission(Android.Manifest.Permission.AccessCoarseLocation)]
[assembly: UsesPermission(Android.Manifest.Permission.AccessFineLocation)]
[assembly: UsesFeature("android.hardware.location", Required = false)]
[assembly: UsesFeature("android.hardware.location.gps", Required = false)]
[assembly: UsesFeature("android.hardware.location.network", Required = false)]
ios的專案的設定:
Info.plist用文字編輯器打開,並且加入下面內容
<key>NSLocationWhenInUseUsageDescription</key>
<string>在這邊填寫入為什麼您需要存取使用者位置的權限.</string>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
上面是設定的部分,接下來是怎麼在程式碼中呼叫
然後於任何一個類別(例如你的商業邏輯.cs裡面),加入下面GetCurrentLocation()這個function,用來取得目前的使用者位置
ps.當你以同步的方式去呼叫GetCurrentLocation()的時候,GetCurrentLocation()的boolSetTimeout參數必須為true,隨便設定個3秒也可以
public static async Task<Location> GetCurrentLocation(bool boolSetTimeout = true,
double timeoutMilliseconds = 1000)
{
try
{
GeolocationRequest request;
if (boolSetTimeout == true)
{
request = new GeolocationRequest(GeolocationAccuracy.High,
TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
else
{
request = new GeolocationRequest(GeolocationAccuracy.High);
}
if ((DateTime.Now - LatestGetLocationTime).TotalSeconds > 300
|| LatestLocation == null)
{
//超過300秒就重新取目前位置
var location = await Geolocation.GetLocationAsync(request);
if (location != null)
{
//Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
LatestLocation = location;
LatestGetLocationTime = DateTime.Now;
return location;
}
}
else
{
//不然就取五分鐘之前的
return LatestLocation;
}
}
catch (FeatureNotSupportedException fnsEx)
{
// Handle not supported on device exception
}
catch (FeatureNotEnabledException fneEx)
{
// Handle not enabled on device exception
}
catch (PermissionException pEx)
{
// Handle permission exception
}
catch (Exception ex)
{
// Unable to get location
}
return null;
}
在.xaml.cs裡面要引用上面這個function的時候,像是下面這樣呼叫即可(下面這是以非同步的方式呼叫,建議使用非同步方式,盡量不要用同步的方式去call)
var currentLocation = await Utils.GetCurrentLocation(false);//目前所在位置
Console.WriteLine(currentLocation.Latitude);
Console.WriteLine(currentLocation.Longitude);
這篇大概是這樣……
參考資料:
Xamarin.Essentials:地理位置
https://docs.microsoft.com/zh-tw/xamarin/essentials/geolocation?tabs=ios
逐步解說-Xamarin 中的背景位置
https://docs.microsoft.com/zh-tw/xamarin/ios/app-fundamentals/backgrounding/ios-backgrounding-walkthroughs/location-walkthrough