如何获取经纬度示例代码

获取经纬度示例代码。

HarmonyOS
2024-06-03 23:28:47
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
juliedan
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%') 
  } 
}
分享
微博
QQ
微信
回复
2024-06-04 22:30:10
相关问题
xComponet示例代码不能使用
475浏览 • 1回复 待解决
有使用华为支付的示例代码
439浏览 • 1回复 待解决
使用华为账号服务登录的示例代码
463浏览 • 1回复 待解决
代码获取后台弹框权限?
1860浏览 • 1回复 待解决
websocket和http数据请求示例
265浏览 • 1回复 待解决
napi 基本使用场景示例
424浏览 • 1回复 待解决
证书锁定功能示例有哪些?
276浏览 • 1回复 待解决
如何通过代码触发APP重启
457浏览 • 1回复 待解决