最近做的项目需要获取经纬度,用的uni-app。这点上几乎完全是小白,看了很多文章才愣是凑出来个能用的。
在环境配置上需要在manifest.json上先配置好小程序id,在网页的开发设置处也需要先引入腾讯地图的接口。同时在app.json处先引入
"requiredPrivateInfos" : ["getLocation"] ,
以上用于事先声明getlocation函数,之后才可以调用
<template>
<div class="map">
<map :latitude="lat" :longitude="lng" style="width: 100%; height: 90%;" :markers="marker"
show-location="true"></map>
</div>
</template><script>
export default {
data() {
return {
lat: 0,
lng: 0,
marker: [{
id: 0,
latitude: 0,
longitude:0,
iconPath: "",
rotate: 0,
width: 40,
height: 60,
alpha: 1
}]
};
},
mounted() { //钩子函数,进入之后就会立刻调用
this.getLocation();
},
methods: {
// 获取当前位置
getLocation() {
const that = this;
uni.getLocation({
type: 'gcj02',
success(res) {
console.log(res);
that.lat = res.latitude; // 更新经度
that.lng = res.longitude; // 更新纬度
const qqmap = require('@/pages/qqmap-wx-jssdk.min.js');
const showmap = new qqmap({
key: '这里输入腾讯地图的key'
});
showmap.reverseGeocoder({ //地址逆解析函数,具体参考腾讯地图JS SDK
location: {
latitude: res.latitude,
longitude: res.longitude
},
success(result) {
const adres = result.result.address;
that.address = adres;
console.log(adres);
},
fail: (error) => {
console.error(error);
}
});
},
});
}
}
};
</script><style>
.map {
height: 100%;
width: 100%;
position: absolute;
}
</style>
这里获取位置似乎会始终定在一个位置,但是真机测试里是没问题的。