Hello,World.

秋风与你,偏安一隅.

微信小程序制作-随笔2

小程序获取定位信息:

主要采用小程序自带获取经纬度方法与高德api接口结合

    步骤:1.注册高德地图开发者,获取key,从高德里下载微信小程序SDK,导入到项目中。(sdk下载:https://lbs.amap.com/api/wx/download)

    2.将需要的配置文件和引入sdk语句写入页面js的开头

var amapFile = require('导入的sdk文件位置');//注意引入路径
var markersData = {
  latitude: '',//纬度
  longitude: '',//经度
  key: "高德地图key"//申请的高德地图key
};

    3.写微信自带的获取经纬度方法,通过这个方法取到经纬度后传值给调用高德接口的函数。

  loadInfo: function(){
    var that=this;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        var latitude = res.latitude//维度
        var longitude = res.longitude//经度
        console.log(res);
        that.loadCity(latitude,longitude);
      }
    })
  },

    4.调用sdk接口的函数,写入页面js中。

loadCity: function (latitude, longitude){
    var that=this;
    var myAmapFun = new amapFile.AMapWX({ key: markersData.key });
    myAmapFun.getRegeo({
      location: '' + longitude + ',' + latitude + '',//location的格式为'经度,纬度'
      success: function (data) {
        console.log(data);
      },
      fail: function (info) { }
    });

    myAmapFun.getWeather({
      success: function (data) {
        that.setData({
          weather: data
        })
        console.log(data);
        //成功回调
      },
      fail: function (info) {
        //失败回调
        console.log(info)
      }
    })
  },

    5.调用,在onLoad函数中调用这两个方法即可看到输出数据和给前台传值。

  onLoad: function (options) {
    this.loadInfo();
    this.loadCity();
  },

    6.取值,前台取值通过weather.***来取值。

{{weather.city.data}}//城市信息
{{weather.weather.data}} 
{{weather.winddirection.data}} 
{{weather.windpower.data}}
{{weather.temperature.data}}//具体的自己查看输出内容

注意:此处调用后这些函数后运行可能会报request:fail url not in domain list的错,是因为url不合法或其他域名不合法原因,此时去右上角详情里把不校验合法性勾上即可。

 

posted @ 2019-01-31 13:16  秋风荡  阅读(226)  评论(0编辑  收藏  举报