uniapp微信小程序獲取當(dāng)前定位城市信息的實(shí)例代碼
一、事先準(zhǔn)備
此處用的是騰訊地圖的jdk


1、在騰訊地圖開發(fā)上申請(qǐng)key
2、 WebServiceAPI選擇簽名校驗(yàn)獲取SK
3、 uniapp上勾選位置接口
4、在騰訊地圖上下載微信小程序javaScript SDK放入項(xiàng)目里
二、正式代碼使用
提示:可能會(huì)出現(xiàn)引入jdk時(shí)報(bào)錯(cuò)
解決方法:
*把jdk最后一行暴漏方式改為export default 引入時(shí)用import就行了*
// 1、首先在需要用到的地方引入下載的jdk
import QQMapWx from '../../common/qqmap-wx-jssdk.min.js'
// 2、通過騰訊地圖key初始化
const qqmapSdk = new QQMapWx({
key: 'xxxxxxx' // 在騰訊地圖上申請(qǐng)的key
})
// 3、獲取微信定位授權(quán)方法
getAuthorize () {
uni.authorize({
scope: 'scope.userLocation',
success: (res) => {
this.getLocation()
},
fail: (err) => {
uni.showModal({
content: '需要授權(quán)位置信息',
confirmText: '確認(rèn)授權(quán)'
}).then(res => {
if (res['confirm']) {
uni.openSetting({
success: res => {
if (res.authSetting['scope.userLocation']) {
uni.showToast({
title: '授權(quán)成功',
icon: 'none'
})
} else {
uni.showToast({
title: '授權(quán)失敗',
icon: 'none'
})
}
this.getLocation()
}
})
}
if (res['cancel']) {
// 取消授權(quán)
this.getLocation()
}
})
}
})
}
// 4、開始獲取定位方法
getLocation () {
uni.getLocation({
type: 'gcj02',
success: (res) => {
const { latitude, longitude } = res
qqmapSdk.reverseGeocoder({
location: latitude ? `${latitude},${longitude }` : '',
sig: 'xxxx', // 這個(gè)sig就是上面要準(zhǔn)備的第二項(xiàng)SK
success: (val) => {
console.log('這就是要獲取的當(dāng)前所在城市的相關(guān)信息', val)
},
fail: (err) => {
console.log('獲取城市失敗')
}
})
},
fail: (err) => {
if (err.errMsg === 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF' || err.errMsg === 'getLocation:fail system permission denied') {
uni.showModal({
content: '請(qǐng)開啟手機(jī)定位服務(wù)',
showCancel: false
})
} else if (err.errMsg === 'getLocation:fail:system permission denied') {
uni.showModal({
content: '請(qǐng)給微信開啟定位權(quán)限',
showCancel: false
})
}
}
})
}
補(bǔ)充:UNIAPP獲取當(dāng)前城市和坐標(biāo)
uni.getLocation({
type: 'wgs84',
success: res=> {
console.log(res)
console.log('當(dāng)前位置的經(jīng)度:' + res.longitude);
console.log('當(dāng)前位置的緯度:' + res.latitude);
}
});總結(jié)
到此這篇關(guān)于uniapp微信小程序獲取當(dāng)前定位城市信息的文章就介紹到這了,更多相關(guān)uniapp小程序獲取定位城市內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
jquery SweetAlert插件實(shí)現(xiàn)響應(yīng)式提示框
為了滿足用戶體驗(yàn)度,使用SweetAlert插件實(shí)現(xiàn)響應(yīng)式提示框效果非常好,下面通過這篇文章給大家介紹jquery SweetAlert插件實(shí)現(xiàn)響應(yīng)式提示框,需要的朋友可以參考下2015-08-08
js仿蘋果iwatch外觀的計(jì)時(shí)器代碼分享
這篇文章主要介紹了JS+CSS3實(shí)現(xiàn)的類似于蘋果iwatch計(jì)時(shí)器特效,很實(shí)用的代碼,推薦給大家,有需要的小伙伴可以參考下。2015-08-08
簡(jiǎn)單了解JavaScript arguement原理及作用
這篇文章主要介紹了簡(jiǎn)單了解JavaScript arguement原理及作用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05

