最近做項目需要用到 微信公衆號獲取定位,並將定位轉換爲具體地址的需求,找了挺多,最後整理下,分享給大家~
我這裏使用的是騰訊地圖,也可以使用其他的如百度、高德等。
思路是,先使用微信開放文檔的獲取定位接口進行獲取定位(這裏的定位是經緯度),然後使用騰訊地圖將經緯度定位轉換爲具體所在的地址。
前提準備:
1、首先先申請一個騰訊地圖key
網址爲:申請騰訊地圖的開發者key https://lbs.qq.com/console/mykey.html?console=mykey,申請完以後是這樣
2、項目安裝 wx依賴
npm install weixin-js-sdk --save-dev
接下來就是代碼操作:
1、先要引入wx和騰訊地圖
在項目的index.html頁面引入騰訊地圖
<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=自己的key"></script> <!-- 騰訊地圖 -->
在需要獲取定位的頁面引入wx
//引入微信
import wx from 'weixin-js-sdk'
2、接下來就是獲取微信定位
在獲取微信定位的時候,要先通過config接口注入權限驗證配置,獲取配置信息裏面的內容是後端接口給出的,所用的接口域名一定要備案。
所有需要使用JS-SDK的頁面必須先注入配置信息,否則將無法調用
wx.config({
debug: true, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
appId: '', // 必填,公衆號的唯一標識
timestamp: , // 必填,生成簽名的時間戳
nonceStr: '', // 必填,生成簽名的隨機串
signature: '',// 必填,簽名
jsApiList: [] // 必填,需要使用的JS接口列表
});
具體代碼如下:(在<script></script>標籤中)
data () {
return {
configContent: [],
address: []
}
},
mounted () {
this.setWxjs()
},
setWxjs () {
let url = encodeURIComponent(window.location.href.split('#')[0])
this.$axios.get('這裏是後端提供的接口?url=' + url).then(res => {
if (res.data.code === 0) {
this.configContent = res.data.data
this.signWX()
}
})
},
signWX () {
let _this = this
wx.config({
debug: true, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
appId: this.configContent.appId, // 必填,公衆號的唯一標識
timestamp: this.configContent.timestamp, // 必填,生成簽名的時間戳
nonceStr: this.configContent.nonceStr, // 必填,生成簽名的隨機串
signature: this.configContent.signature, // 必填,簽名
jsApiList: ['checkJsApi', 'openLocation', 'getLocation', 'updateAppMessageShareData', 'updateTimelineShareData'] // 必填,需要使用的JS接口列表
})
wx.checkJsApi({
jsApiList: ['getLocation'],
success: function (res) {
// alert(JSON.stringify(res));
if (res.checkResult.getLocation === false) {
alert('你的微信版本太低,不支持微信JS接口,請升級到最新的微信版本!')
return false
}
}
})
wx.ready(function () {
wx.getLocation({
type: 'gcj02', // 默認爲wgs84的gps座標,如果要返回直接給openLocation用的火星座標,可傳入'gcj02'
success: function (res) {
// 獲取經緯度
var latLng = new qq.maps.LatLng(res.latitude, res.longitude)
getAddr.getAddress(latLng)
},
cancel: function (res) {
alert('用戶拒絕授權獲取地理位置')
}
})
})
wx.error(function (res) {
console.log('微信js-sdk 配置失敗000' + res.errMsg)
// alert('微信js-sdk 配置失敗000' + res.errMsg)
})
// 調取騰訊地圖
var getAddr = new qq.maps.Geocoder({
complete: function (res) {
_this.address = res.detail
var allAddress = res.detail.addressComponents
// _this.address = res.detail.nearPois
var address = res.detail.address
// alert('地址:' + JSON.stringify(_this.address))
console.log('地址:', address, allAddress.province, allAddress.city, allAddress.district)
// alert('地址:' + address + allAddress.province + allAddress.city + allAddress.district)
}
})
}
以上就是關於微信獲取定位經緯度,並通過騰訊地圖調用逆地址解析的方法將微信獲取到的經緯度轉換爲具體的地址,如北京市朝陽區,有哪裏理解的不對的地方,歡迎指正~