- 在
app.json
中開發小程序的接口權限,設置permission
的權限,在裏面配置scope.userLocation
,開放位置權限,代碼如下所示:
"permission": {
"scope.userLocation": {
"desc": "你的位置信息將用於小程序位置接口的展示"
}
},
- 在頁面
indx.wxml
中,調用map
的信息,代碼如下所示:
<map id="map" longitude="{{longitude}}" latitude="{{latitude}}" scale="14" class="map"></map>
- 在
data
中定義經度和緯度信息,設置longitude
和latitude
的值爲空,代碼如下所示:
longitude: "",
latitude: ""
- 在頁面當中
index.js
進行相應的配置,在Page
中,onShow()
方法調用一個獲取位置的函數,使得一進入頁面的時候,就會執行,獲取到當前的位置信息,代碼如下所示:
onShow() {
this.getLocation()
}
- 在
Page
中定義getLocation()
函數,寫上wx.getLocation()
方法,獲取到當前的地理位置,在裏面定義type
類型爲gcj02
,同時調用成功後的回調函數,代碼如下所示:
getLocation() {
wx.getLocation({
type: 'gcj02',
success: this.getLocationSucces.bind(this)
})
}
- 在
Page
中定義getLocationSucces()
函數,通過this.setData()
方法,將響應獲得的經度和緯度值賦值給當前的經度和緯度值,就可以成功使用地圖開發獲取到當前的位置信息,代碼如下所示:
getLocationSucces(res) {
this.setData({
longitude: res.longitude,
latitude: res.latitude
})
}