uniapp获取当前位置和经纬度信息
1.1. 获取当前位置和经纬度信息(需要配置高的SDK)
调用uni-app
官方API中的uni.chooseLocation()
,即打开地图选择位置。
<button @click="getAddress">获取定位</button>
const getAddress = () => {uni.chooseLocation({success: res => {console.log(res);console.log('位置名称:' + res.name);console.log('详细地址:' + res.address);console.log('纬度:' + res.latitude);console.log('经度:' + res.longitude);}});
}
- res打印结果如下
{"name": "雨花街道民智路12-5号南京证大喜玛拉雅中心","latitude": 31.964383,"longitude": 118.804811,"address": "江苏省南京市雨花台区雨花街道民智路12-5号南京证大喜玛拉雅中心","errMsg": "chooseLocation:ok"
}
1.2. 如果只是简单获取经纬度信息uni.getLocation即可满足条件
const getAddress = () => {uni.getLocation({type: 'wgs84',success: function(res) {console.log(res);},fail: function(error) {console.error('获取位置失败:', error);}});
}
- res打印结果如下
{"type": "wgs84","altitude": 0,"latitude": 31.966442,"longitude": 118.799641,"speed": 0.036327,"accuracy": 32,"errMsg": "getLocation:ok"
}
1.3. 如果需要获取省市区以及区域编码(需要配置高的SDK)
// 获取经纬度 省市区 详细地址
const chooseLocation = () => {uni.getLocation({// gcj02 返回国测局坐标(App 和 H5 需配置定位 SDK 信息才可支持 gcj02。)type: 'gcj02', // 是否解析地址信息(仅App平台支持(安卓需指定 type 为 gcj02 并配置三方定位SDK))geocode: true, success: function(res) {console.log(res);}});
}
- res打印结果如下
{"type": "gcj02","altitude": 0,"latitude": 31.96437,"longitude": 118.804836,"speed": 0,"accuracy": 34,"address": {"country": "中国","province": "江苏省","city": "南京市","district": "雨花台区","street": "民智路","streetNum": "12-2号","poiName": "喜玛拉雅中心C座","cityCode": "025"},"errMsg": "getLocation:ok"
}