获取手机的当前位置
-
在 Visual Studio 中创建新的 Windows Phone 应用。
-
在“解决方案资源管理器”中,展开“属性”文件夹,然后双击 WMAppManifest.xml。
-
在清单设计器的“功能”选项卡上,选中“ID_CAP_LOCATION”旁边的复选框。
-
在 MainPage.xaml 中,将下列 XAML 代码粘贴到现有的名为 ContentPanel 的 Grid 元素上。此代码定义一个将启动位置 API 的按钮,以及一些文本块来显示维度、经度和应用的状态。
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <Button x:Name="OneShotLocationButton" Click="OneShotLocation_Click" Content="get one-shot location"/> <TextBlock x:Name="LatitudeTextBlock"/> <TextBlock x:Name="LongitudeTextBlock"/> <TextBlock x:Name="StatusTextBlock"/> </StackPanel> </Grid>
-
在 MainPage.xaml.cs 文件的顶部添加以下 using 语句。
using System.Threading.Tasks; using Windows.Devices.Geolocation;
-
添加同意提示以允许用户选择不让您的应用访问其位置。所有应用在使用位置 API 之前,应取得用户同意。本例检查 MainPage 类的OnNavigatedTo(NavigationEventArgs) 方法中的用户同意,只要应用启动,就会调用它。代码首先检查 ApplicationSettings 字典,以了解是否存在“LocationConsent”密钥。如果发现该密钥,则意味着用户已经选择或退出位置,因此该方法立即返回。如果未发现该密钥,那么将显示 MessageBox,寻求用户同意。MessageBox 操作的结果受到检查,指示用户同意状态的布尔值存储在 ApplicationSettings 中的“LocationConsent”密钥内。在应用尝试访问用户位置之前,此密钥将受到检查。
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent")) { // User has opted in or out of Location return; } else { MessageBoxResult result = MessageBox.Show("This app accesses your phone's location. Is that ok?", "Location", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true; }else { IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false; } IsolatedStorageSettings.ApplicationSettings.Save(); } }
-
将下列处理程序粘贴到用于按钮单击事件的 MainPage.xaml.cs 中。该方法首先检查 ApplicationSettings 字典中用户同意的状态。如果值为 false,则该方法立即退出。一旦确定用户同意,则该方法初始化 Geolocator 对象,并设置 DesiredAccuracyInMeters 属性。随后,将调用 GetGeopositionAsync 方法。此方法尝试获取手机的当前位置。此为异步操作,因此在获取位置时不会阻止 UI 线程。您可以使用 await 操作符将代码置于异步调用之后,将在调用完成后执行。这需要该处理程序方法被申明为 async。因为可以确保使用 await 发起的调用返回在调用开始的线程上,而且 await 调用从 UI 线程发起,因此代码可以在调用返回时,直接访问并修改 UI。
整个位置操作都包装在 try 块中,以防止引发任何异常。如果在开发时引发 UnauthorizedAccessException 异常,可能意味着您的应用清单中未包含 ID_CAP_LOCATION。如果在已经部署应用之后发生这种情况,则可能意味着用户已在手机“设置”中禁用了此应用的位置。
private async void OneShotLocation_Click(object sender, RoutedEventArgs e) { if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true) { // The user has opted out of Location. return; } Geolocator geolocator = new Geolocator(); geolocator.DesiredAccuracyInMeters = 50; try { Geoposition geoposition = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); LatitudeTextBlock.Text = geoposition.Coordinate.Latitude.ToString("0.00"); LongitudeTextBlock.Text = geoposition.Coordinate.Longitude.ToString("0.00"); } catch (Exception ex) { if ((uint)ex.HResult == 0x80004004) { // the application does not have the right capability or the location master switch is off StatusTextBlock.Text = "location is disabled in phone settings."; } //else { // something else happened acquring the location } } }