微信小程序如何使用地圖開發獲取位置信息

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