获取手机的当前位置

获取手机的当前位置

  1. 在 Visual Studio 中创建新的 Windows Phone 应用。

  2. “解决方案资源管理器”中,展开“属性”文件夹,然后双击 WMAppManifest.xml。

  3. 在清单设计器的“功能”选项卡上,选中“ID_CAP_LOCATION”旁边的复选框。

  4. 在 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>
    
    
    
  5. 在 MainPage.xaml.cs 文件的顶部添加以下 using 语句。

    C#
    using System.Threading.Tasks;
    using Windows.Devices.Geolocation;
    
    
    
  6. 添加同意提示以允许用户选择不让您的应用访问其位置。所有应用在使用位置 API 之前,应取得用户同意。本例检查 MainPage 类的OnNavigatedTo(NavigationEventArgs) 方法中的用户同意,只要应用启动,就会调用它。代码首先检查 ApplicationSettings 字典,以了解是否存在“LocationConsent”密钥。如果发现该密钥,则意味着用户已经选择或退出位置,因此该方法立即返回。如果未发现该密钥,那么将显示 MessageBox,寻求用户同意。MessageBox 操作的结果受到检查,指示用户同意状态的布尔值存储在 ApplicationSettings 中的“LocationConsent”密钥内。在应用尝试访问用户位置之前,此密钥将受到检查。

    C#
    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();
        }
    }
    
    
    
  7. 将下列处理程序粘贴到用于按钮单击事件的 MainPage.xaml.cs 中。该方法首先检查 ApplicationSettings 字典中用户同意的状态。如果值为 false,则该方法立即退出。一旦确定用户同意,则该方法初始化 Geolocator 对象,并设置 DesiredAccuracyInMeters 属性。随后,将调用 GetGeopositionAsync 方法。此方法尝试获取手机的当前位置。此为异步操作,因此在获取位置时不会阻止 UI 线程。您可以使用 await 操作符将代码置于异步调用之后,将在调用完成后执行。这需要该处理程序方法被申明为 async。因为可以确保使用 await 发起的调用返回在调用开始的线程上,而且 await 调用从 UI 线程发起,因此代码可以在调用返回时,直接访问并修改 UI。

    整个位置操作都包装在 try 块中,以防止引发任何异常。如果在开发时引发 UnauthorizedAccessException 异常,可能意味着您的应用清单中未包含 ID_CAP_LOCATION。如果在已经部署应用之后发生这种情况,则可能意味着用户已在手机“设置”中禁用了此应用的位置。

    C#
    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
            }
        }
    }
    
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用pyQt实现手机app获取当前手机地理位置,需要使用QGeoPositionInfoSource类。该类提供了获取设备位置的API,可以通过该类获取设备的地理位置信息。 以下是实现步骤: 1.导入必要的模块: ``` from PyQt5.QtCore import QGeoPositionInfoSource, QGeoPositionInfo, Qt from PyQt5.QtGui import QTextCursor from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout ``` 2.创建主窗口和文本框: ``` class MainWindow(QWidget): def __init__(self): super().__init__() self.setGeometry(100, 100, 600, 400) self.setWindowTitle('获取设备位置') self.text_edit = QTextEdit() self.text_edit.setReadOnly(True) layout = QVBoxLayout() layout.addWidget(self.text_edit) self.setLayout(layout) ``` 3.创建位置信息源: ``` class LocationInfoSource: def __init__(self, parent): self.parent = parent self.position_info_source = QGeoPositionInfoSource.createDefaultSource(parent) ``` 4.连接位置更新信号: ``` def start(self): if self.position_info_source: self.position_info_source.positionUpdated.connect(self.on_position_updated) self.position_info_source.startUpdates() def on_position_updated(self, info): position = info.coordinate() latitude = position.latitude() longitude = position.longitude() text = f'纬度: {latitude}, 经度: {longitude}' self.parent.append_text(text) ``` 5.实现文本框的更新: ``` def append_text(self, text): cursor = self.text_edit.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text + '\n') self.text_edit.setTextCursor(cursor) self.text_edit.ensureCursorVisible() ``` 6.启动应用程序: ``` if __name__ == '__main__': app = QApplication([]) window = MainWindow() location_info_source = LocationInfoSource(window) location_info_source.start() window.show() app.exec_() ``` 完整代码如下: ``` from PyQt5.QtCore import QGeoPositionInfoSource, QGeoPositionInfo, Qt from PyQt5.QtGui import QTextCursor from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout class MainWindow(QWidget): def __init__(self): super().__init__() self.setGeometry(100, 100, 600, 400) self.setWindowTitle('获取设备位置') self.text_edit = QTextEdit() self.text_edit.setReadOnly(True) layout = QVBoxLayout() layout.addWidget(self.text_edit) self.setLayout(layout) def append_text(self, text): cursor = self.text_edit.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text + '\n') self.text_edit.setTextCursor(cursor) self.text_edit.ensureCursorVisible() class LocationInfoSource: def __init__(self, parent): self.parent = parent self.position_info_source = QGeoPositionInfoSource.createDefaultSource(parent) def start(self): if self.position_info_source: self.position_info_source.positionUpdated.connect(self.on_position_updated) self.position_info_source.startUpdates() def on_position_updated(self, info): position = info.coordinate() latitude = position.latitude() longitude = position.longitude() text = f'纬度: {latitude}, 经度: {longitude}' self.parent.append_text(text) if __name__ == '__main__': app = QApplication([]) window = MainWindow() location_info_source = LocationInfoSource(window) location_info_source.start() window.show() app.exec_() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值