- 代码
uni.getLocation({
type: 'wgs84',
success: function (res) {
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
}
});
注意点
在测试获取时,不要谷歌浏览器.真的不要用那个 真的…
获取经纬度后,进行逆编理(这块使用的是百度的)
uni.request({
header: {
"Content-Type": "application/text"
},
url: 'http://api.map.baidu.com/reverse_geocoding/v3/?ak=(这块写自己申请的ak,现在需要实名申请web端的就行)=' +res.latitude + ',' + res.longitude + '&output=json&pois=1',
//这里直接调用会报跨域问题下面会说明解决跨域
success(re) {
if (re.statusCode === 200) {
//获取成功后格式要进行处理
const subData = re.data.substring(re.data.indexOf("(") + 1, re.data.lastIndexOf(")")); //这个处理格式
console.log("中文位置", JSON.parse(subData).result.addressComponent)//转化为对象格式
} else {
console.log("获取信息失败,请重试!")
}
}
});
这会说一下解决跨域,(uniapp 只有H5会有问题)
打开manifest.json文件点击源码视图(原理还是使用代理)
找到’H5’那个属性
"h5": {
//添加这个里面别的代码不要删除然后将上面的http://api.map.baidu.com 用/api代替(记得一定要替换)
"devServer": {
"disableHostCheck": true,
"proxy": {
"/api": {
"target": "http://api.map.baidu.com",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/api": ""
}
}
}
}
}
大多数人想要改造这个世界,但却罕有人想改造自己。