生活随笔
收集整理的這篇文章主要介紹了
小程序 获取当前用户地址及地图显示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
步驟
使用 wx.getLocation來獲取當前位置:
注意;當用戶取消位置獲取授權之后,再次點擊獲取位子按鈕小程序不會再提醒用戶是否授權,這個時候最好自己彈出提示框讓用戶去設置頁面開啟授權設置.
wx
.getLocation({type
: 'wgs84', altitude
: 'false' success (res
) { const latitude
= res
.latitude
const longitude
= res
.longitude
const speed
= res
.speed
const accuracy
= res
.accuracy
const altitude
= res
.altitude
...},fail (err
) { },complete(){}
})
注意:
工具中定位模擬使用
IP定位,可能會有一定誤差。且工具目前僅支持 gcj02 坐標。
使用第三方服務進行逆地址解析時,請確認第三方服務默認的坐標系,正確進行坐標轉換。
(后面需要使用獲取到的數據打開微信內置地圖
,最好使用gjc02)
使用 wx.openLocation打開地址位置:
將經緯度傳進去就可以打開地圖并標記當前位置.
wx
.getLocation({type
: 'gcj02', success (res
) {const latitude
= res
.latitude
const longitude
= res
.longitudewx
.openLocation({latitude
,longitude
,scale
: 18})}
})
微信公眾平臺
API:https
://developers
.weixin
.qq
.com
/miniprogram
/dev
/api
/location
/wx
.openLocation
.html
使用wx.chooseLocation來打開地圖選擇位置.(建議在手機上調試)
wx
.getLocation({type
: 'gcj02', success (res
) {const latitude
= res
.latitude
const longitude
= res
.longitudewx
.openLocation({latitude
,longitude
,wx
.chooseLocation({success
: function(res
) {console
.log('定位成功')},})})}
})
實例
<button bindtap
="getLocation">獲取當前地址
</button
>getLocation () {let _this
= thiswx
.getLocation({type
: 'gcj02',success(res
) {console
.log('獲取地理經緯度成功' + res
)_this
.setData({latitude
: res
.latitude
,longitude
: res
.longitude
})wx
.openLocation({latitude
: res
.latitude
,longitude
: res
.longitude
,scale
: 18,success(res
){console
.log('打開地址位置成功')wx
.chooseLocation({success
: function(res
) {console
.log('定位成功')},fail(err
){console
.log('定位失敗' + err
)}})}})},fail(err
){console
.log(err
)}})},缺點:地獄回調,建議異步
缺陷:
使用 wx.getLocation來獲取當前位置時:當用戶使用 wx.getLocation來獲取當前位置,取消位置獲取授權之后,再次點擊獲取位子按鈕小程序不會再提醒用戶是否授權,這個時候最好自己彈出提示框讓用戶去設置頁面開啟授權設置
解決辦法: 添加用戶是否初次進入該頁面以及是否地理位置授權的判斷
代碼:
wx
.getSetting({success
: (res
) => {console
.log(JSON.stringify(res
))if (res
.authSetting
['scope.userLocation'] != undefined
&& res
.authSetting
['scope.userLocation'] != true) {wx
.showModal({ title
: '請求授權當前位置',content
: '需要獲取您的地理位置,請確認授權',success (res
) {if (res
.cancel
) {wx
.showToast({title
: '拒絕授權',icon
: 'none',duration
: 1000})} else if (res
.confirm
) {wx
.openSetting({success (dataAu
) {if (dataAu
.authSetting
["scope.userLocation"] == true) {wx
.showToast({title
: '授權成功',icon
: 'success',duration
: 1000})} else {wx
.showToast({title
: '授權失敗',icon
: 'none',duration
: 1000})}}})}}})} else if (res
.authSetting
['scope.userLocation'] == undefined
) {}else {}}})
總結
以上是生活随笔為你收集整理的小程序 获取当前用户地址及地图显示的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。