微信小程序API——获取定位

<view class=content>
  <view class=today>
    <view class=info>
      <view class=temp>{
          
   {
          
   weather.temperature.data}}℃</view>
      <view class=weather>{
          
   {
          
   weather.weather.data}} {
          
   {
          
   weather.winddirection.data}} {
          
   {
          
   weather.windpower.data}}</view>
      <view>友情提示:今天天气不错,是风和日丽的,适合出去玩</view>
      <view class=city>{
          
   {
          
   weather.city.data}}</view>
    </view>
  </view>
</view>

首先给出我的前端代码,中括号内的变量就是我们下文中从高德地图返回给我们的json数组中解析出来的。下面让我们来看一下我们如何获得当前的定位以及获取高德地图给我们的信息。

//获取当前位置的经纬度
  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);
      }
    })
  },
var amapFile = require(../../libs/amap-wx.js);
var markersData = {
  latitude: ,//纬度
  longitude: ,//经度
  key: "需要去高德地图注册成为开发者,然后就会获得一个key"//申请的高德地图key
};

好了,我们配置好外部文件以后,就可以在js里面写逻辑了,下面贴出我的js代码。

var amapFile = require(../../libs/amap-wx.js);
var markersData = {
  latitude: ,//纬度
  longitude: ,//经度
  key: "高德地图key"//申请的高德地图key
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    weather:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
          
   
    this.loadInfo();
  },


  //获取当前位置的经纬度
  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);
      }
    })
  },

  //把当前位置的经纬度传给高德地图,调用高德API获取当前地理位置,天气情况等信息
  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)
      }
    })
  },


})

我们在onload函数中获取当前的定位,我们把经纬度信息传递给myAmapFun.getRegeo方法中的location参数,接下来我们可以看看高德地图给我们返回的信息。

我们获取了我们的位置以及邮政编码等一系列信息,大家可以去高德地图上注册一个开发者,得到一个key,然后测试一下,也可以获得你们当地的信息。

我们再看一下myAmapFun.getWeather给我们返回的天气信息。

我们顺利得到了我们当地的天气信息,然后再把这些信息显示在我们的wxml界面就行了,大家注意一下图片中的属性,然后再看一下wxml中括号内的变量,就可以知道讲json数组的某些属性的值如何传到前端了。有一个细节就是我把myAmapFun.getWeather方法返回的data数组传给了我在全局data中定义的weather数组,这样我们在前端就可以通过上文wxml中的方法来显示数组中的值。

经验分享 程序员 微信小程序 职场和发展