用uniapp写小程序实现简单的获取当前城市定位的demo
先上代码
<template>
<view>
{{currentCity || '广州'}}
</view>
</template>
<script>
var QQMapWX = require('../../static/js/qqmap-wx-jssdk.min.js');
export default {
data() {
return {
currentCity:''
}
},
onReady(){
this.getCity()
},
methods: {
getCity(){
// console.log(uni)
let that = this;
// 获取用户权限
uni.authorize({
scope:"scope.userLocation",
success(){
// 引入腾讯地图api
let qqmapsdk = new QQMapWX({
key:'RAQBZ-ELHLJ-XSHFY-KZYPD-B7PCO-EFF2W'
});
// 获取定位信息
uni.getLocation({
type:'gcj02',
success(res){
// console.log(res.longitude);
// console.log(res.latitude);
// 逆地址解析
qqmapsdk.reverseGeocoder({
location:{
latitude: res.latitude,
longitude: res.longitude
},
success(res){
that.currentCity = res.result.address_component.city;
console.log(that.currentCity)
}
})
}
})
},
fail(err){
console.log(err)
}
})
}
}
}
</script>
<style>
</style>
首先需要获取用户权限 uni.authorize
同时要开启位置接口配置
其次获取定位信息 uni.getLocation
使用的是腾讯地图api
需要下载微信小程序JavaScriptSDK才能使用,腾讯地图文档中有详细介绍 官方文档