小程序开发笔记【四】,集成高德地图进行逆地址解析

微信小程序获取及选择位置

  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并没有提供获取省份城市的信息,这里使用高德第三方地图来获取省份城市

  1. 申请高德key

  2. 将https://restapi.amap.com添加到微信小程序合法域名里面

  3. 下载高德微信小程序sdk

    https://lbs.amap.com/api/wx/download

高德微信小程序sdk文档说明

https://lbs.amap.com/api/wx/reference/core

  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)
                }
              })