mpvue开发微信小程序定位功能获取城市名及code码(原生获取经纬度高德解析,完整代码)

先上效果图:

mpvue开发微信小程序定位功能获取城市名及code码(原生获取经纬度高德解析,完整代码)_第1张图片

说明: 用了原生的wx.getLocation 定位功能获取 经纬度,然后通过高德解析位置(可以获取位置信息,及附近地址,天气等)

准备:需要下载高德小程序位置组件https://lbs.amap.com/api/wx/download

配置:在创建的项目中,新建一个名为 libs 目录,将 amap-wx.js (amap-wx.js  从相关下载页面下载的 zip 文件解压后得到)文件拷贝到 libs 的本地目录下,如下图所示。

mpvue开发微信小程序定位功能获取城市名及code码(原生获取经纬度高德解析,完整代码)_第2张图片mpvue开发微信小程序定位功能获取城市名及code码(原生获取经纬度高德解析,完整代码)_第3张图片

引用高德组件

mpvue开发微信小程序定位功能获取城市名及code码(原生获取经纬度高德解析,完整代码)_第4张图片

(下面有完整代码包含城市锚点滚动功能)主要代码如下:

import amapFile from'../../libs/amap-wx.js'  //记着引用



methods: {
    //定位城市
    gpsCity(){      
      var that=this;
      //调用自带位置获取
      wx.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function (res) {
          var latitude = res.latitude//维度
          var longitude = res.longitude//经度
          that.loadCity(latitude,longitude);//调用高德
        }
      })
    },
    //把当前位置的经纬度传给高德地图,调用高德API获取当前地理位置,天气情况等信
    loadCity(latitude, longitude){
      var that=this;
      var myAmapFun = new amapFile.AMapWX({ key: that.markersData.key });

      myAmapFun.getRegeo({
        location: '' + longitude + ',' + latitude + '',//location的格式为'经度,纬度'
        success: function (data) {
          console.log(data);//全部数据
          var cityCode=data[0].regeocodeData.addressComponent.adcode//获取城市code
          that.gpsCode=cityCode
          that.city_name=data[0].regeocodeData.addressComponent.province//获取省份名称

          console.log(that.gpsCode);
          console.log(that.city_name);
          
        },
        fail: function (info) {}
      });

    },
}

 

完整页面代码如下(包含锚点滚动城市列表功能博客有篇文章介绍此功能):






 

 

 

 

 

你可能感兴趣的:(微信小程序,mpvue,MpVue,微信小程序)