這個(gè)迭代使用mpvue框架開發(fā)了小程序。對(duì)于之前一直用vue來開發(fā)web項(xiàng)目的我來說,有這么一個(gè)框架來開發(fā)小程序真的是很激動(dòng)啊,提升了很多開發(fā)效率。
這里記錄一下在小程序中使用騰訊地圖來定位當(dāng)前城市的功能。

image.png
分析一下思路:

image.png
接下來需要做的事情如下:
1、接入騰訊地圖SDK
文檔地址:https://lbs.qq.com/qqmap_wx_jssdk/index.html
按照文檔的步驟來:

image.png
前3步都很簡(jiǎn)單,第4步需要注意一點(diǎn)的就是,如果你是在開發(fā)工具調(diào)試的話,可以直接勾選這個(gè)使用:

image.png
但是,如果要發(fā)體驗(yàn)版或者發(fā)布正式環(huán)境了之后,就要加上合法域名了,不然使用不了。添加合法域名就是在小程序的管理后臺(tái)這個(gè)地方加入即可。

image.png
準(zhǔn)備工作就是這么多?,F(xiàn)在可以寫代碼了。
2、引入核心代碼,并初始化
//qqmap-wx-jssdk.min.js是下載下來的包,放在utils 或者static目錄下都行
let QQMapWX = require('../../../../static/js/qqmap-wx-jssdk.min.js')
let qqmapsdk
export default {
data() {
return {
city: '',
userLocation: {
latitude: '',
longitude: ''
}
}
},
onLoad() {
qqmapsdk = new QQMapWX({
key: 'xxxxxxxxxxxxxxxxxxxx' // 申請(qǐng)的key
})
this.getUserLocation() //獲取用戶定位
}
},
methods: {
getUserLocation() {
wx.getSetting({ //獲取用戶授權(quán)情況
success: res => {
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { // 用戶非首次訪問,且曾經(jīng)拒絕過授權(quán),此時(shí)res.authSetting['scope.userLocation'] 一般返回false
//這里是跳轉(zhuǎn)開啟定位頁面,引導(dǎo)用戶授權(quán)的代碼
return false
}
this.getLocation() //繼續(xù)下一步
},
fail: () => {
Utils.showToast('網(wǎng)絡(luò)錯(cuò)誤:獲取用戶授權(quán)信息失?。?)
}
})
},
getLocation() {
wx.getLocation({ // 這一步 如果用戶是首次訪問,則會(huì)彈出授權(quán)彈窗
type: 'gcj02',
success: res => {
this.userLocation = res // res包含經(jīng)緯度信息
this.getLocal() //繼續(xù)下一步
},
fail: res => {
if (res.errMsg == 'getLocation:fail 1' || res.errMsg == 'getLocation:fail system permission denied') {
// 用戶允許授權(quán)但獲取位置失敗,可能有多種原因,比如網(wǎng)絡(luò)原因、手機(jī)系統(tǒng)拒絕使用定位
//這里寫相應(yīng)的代碼
} else if (res.errMsg == 'getLocation:fail auth deny' || res.errMsg == 'getLocation:fail:auth denied') {
// 用戶拒絕了授權(quán),跳去開啟定位頁面引導(dǎo)授權(quán)的代碼
} else { // 別的錯(cuò)誤
Utils.showToast('網(wǎng)絡(luò)錯(cuò)誤:獲取用戶所在位置經(jīng)緯度失敗!')
}
}
})
},
getLocal() {
qqmapsdk.reverseGeocoder({
location: {
latitude: this.userLocation.latitude,
longitude: this.userLocation.longitude
},
success: res => {
this.userLocation = {
...this.userLocation,
...res.result
}
this.city = this.userLocation.address_component.city
this.city = this.city.replace('市', '') // 深圳、廣州
},
fail: error => {
Utils.showToast(error.message)
}
})
}
}
整個(gè)流程就是這樣,記錄下來加深記憶的同時(shí)希望能幫助到需要的朋友,如果寫得不明白或者看不懂的歡迎留言。