中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
获取经纬度示例代码。
微信扫码分享
import geoLocationManager from '@ohos.geoLocationManager'; import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; /** 系统定位服务实现 */ @Entry @Component struct Index { //纬度 @State lat: Number = -1; //经度 @State lon: Number = -1; @State message: string = '还没开始哦'; getLocation() { let requestInfo: geoLocationManager.CurrentLocationRequest = { 'priority': 0x203, 'scenario': geoLocationManager.LocationRequestScenario.DAILY_LIFE_SERVICE, 'maxAccuracy': 1000, 'timeoutMs': 5000 }; if (geoLocationManager.isLocationEnabled()) { console.log("AAAAAAAAAAQAAAAAAAAAAAAAAA:定位已使能"); } else { console.log("AAAAAAAAAAQAAAAAAAAAAAAAAA:定位未使能"); } try { geoLocationManager.getCurrentLocation(requestInfo, (err, location) => { if (err) { console.error("定位失败,失败原因为:"); console.error(err.message); return; } console.info("位置获取成功"); this.lat = location.latitude; this.lon = location.longitude; console.info("this.lat = " + this.lat); console.info("this.lon = " + this.lon); setTimeout(() => { this.message = '看见了'; }, 2000); }) } catch (err) { console.error("报错原因为:"); console.error(err); } } how() { abilityAccessCtrl.createAtManager().requestPermissionsFromUser(getContext(), [ 'ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION']).then(() => { }); } build() { Column({ space: 50 }) { Text(this.message) Button() { Text('获取位置') .fontSize(50) } .backgroundColor(Color.Orange) .width(200) .height(100) .onClick(() => { console.log("获取位置已点击"); this.getLocation(); console.info('授权已成功'); }) Text("经度:" + this.lon); Text("纬度:" + this.lat); } .width('100%').height('100%') } }