关于ImToken智能合约交互
2026/5/16 19:35:29
# Flutter × 鸿蒙实战30讲(14):位置服务集成:获取 GPS 坐标 > 作者:烟云任平生 > 发布时间:2025年12月14日 > 标签:`#Flutter` `#OpenHarmony` `#定位` `#GPS` `#CSDN` --- ### 一、应用场景 - 地图展示 - 附近服务 - 轨迹记录 --- ### 二、权限申请 ```json { "requestPermissions": [ { "name": "ohos.permission.LOCATION" }, { "name": "ohos.permission.APPROXIMATELY_LOCATION" } ] } 三、ArkTS 获取位置 // locationBridge.ts import geoLocationManager from '@ohos.geoLocationManager'; export class LocationBridge { static async getCurrentLocation(): Promise<string> { return new Promise((resolve, reject) => { try { geoLocationManager.getCurrentLocation({ success: (location) => { resolve(JSON.stringify({ latitude: location.latitude, longitude: location.longitude, accuracy: location.accuracy })); }, fail: (err) => { reject(err.message); } }); } catch (e) { reject(e.message); } }); } } 四、注册到 WebView // MainPage.ets aboutToAppear() { this.controller.registerJavaScriptProxy({ object: { getLocation: async () => { try { return await LocationBridge.getCurrentLocation(); } catch (e) { return JSON.stringify({ error: e }); } } }, name: "LocationAPI", interface: ["getLocation"] }); } 五、Flutter 侧调用 Future<Map<String, dynamic>> getLocation() async { final bridge = html.window['LocationAPI']; final result = await bridge.callMethod('getLocation'); return jsonDecode(result as String); } // 使用 ElevatedButton( onPressed: () async { final loc = await getLocation(); if (loc['error'] == null) { print('Lat: ${loc['latitude']}, Lng: ${loc['longitude']}'); } }, child: Text('获取位置') ) 六、注意事项 首次调用会弹出 位置权限授权弹窗 模拟器位置固定,建议真机测试 可结合 geoLocationManager.on('locationChange') 实现持续定位 🔜 下一篇预告:《第15讲:蓝牙与 NFC:IoT 场景下的 Flutter 控制面板》 ✨ 定位能力打通,IoT 应用更进一步!