小程序開發筆記【四】,集成高德地圖進行逆地址解析

微信小程序獲取及選擇位置

  1. 獲取當前的地理位置、速度
wx.getLocation({
        type: "wgs84", //wgs84 返回 gps 座標,gcj02 返回可用於 wx.openLocation 的座標  gcj02在android機上有bug,沒法選擇位置
        success(res) {
        }
      });
  1. 打開地圖選擇位置
wx.chooseLocation({
            success(res) {
              let name = res.name; //名稱
              let address = res.address; //詳細地址
              let longitude = res.longitude;//經度
              let latitude = res.latitude;//緯度
                fail: function(info){
                  //失敗回調
                  console.log(info)
                }
              })
            }
          });
  1. 使用微信內置地圖查看位置
openLocation(item){
      let longitude = item.longitude;
      let latitude = item.latitude;
      wx.openLocation({
        latitude,
        longitude,
        scale: 18
      });
    },

逆地址解析(根據經緯度座標獲取城市省份信息)

微信小程序位置api並無提供獲取省份城市的信息,這裏使用高德第三方地圖來獲取省份城市vue

  1. 申請高德key
  2. 將https://restapi.amap.com添加到微信小程序合法域名裏面android

  3. 下載高德微信小程序sdk
    https://lbs.amap.com/api/wx/downloadgit

高德微信小程序sdk文檔說明
https://lbs.amap.com/api/wx/reference/coreweb

  1. 在vue文件中引入
import amapFile from "../../../../../static/sdk/amap-wx";
  1. 初始化地圖及獲取省份城市信息
mounted() {
    this.initMap();
  },
initMap(){
      this.myAmapFun = new amapFile.AMapWX({key:'app key'});
    },

that.myAmapFun.getRegeo({
                location:`${longitude},${latitude}`,
                success: function(data){
                  let province = data[0].regeocodeData.addressComponent.province;
                  let city = data[0].regeocodeData.addressComponent.city;
                  // city:[]
                  if(Object.prototype.toString.call(city)=="[object Array]"){
                    city = city.join('');
                  }
                  that.province = province;
                  that.city = city;
                },
                fail: function(info){
                  //失敗回調
                  console.log(info)
                }
              })

返回參數說明
https://lbs.amap.com/api/webservice/guide/api/georegeo/#regeo小程序

進入小程序讓只初始化一次

  1. 在main.js中引入並初始化
import amapFile from'../static/sdk/amap-wx';
//將其綁定到vue原型上  //使用 this.$myAmapFun訪問
let myAmapFun = new amapFile.AMapWX({ key: 'app key' });
Vue.prototype.$myAmapFun = myAmapFun
  1. vue組件中使用高德地圖
that.$myAmapFun.getRegeo({
                location:`${longitude},${latitude}`,
                success: function(data){
                  let province = data[0].regeocodeData.addressComponent.province;
                  let city = data[0].regeocodeData.addressComponent.city;
                  // city:[]
                  if(Object.prototype.toString.call(city)=="[object Array]"){
                    city = city.join('');
                  }
                  that.province = province;
                  that.city = city;
                },
                fail: function(info){
                  //失敗回調
                  console.log(info)
                }
              })
相關文章
相關標籤/搜索