日期: 2019-06-16 07:34:21 人气: -
在微信小程序中,我们可以很方便的通过API接口来获取我们当前的位置,接下来我讲告诉大家微信获取定位的API—wx.getLocation的用法,以及我们通过获取定位,得到当地的位置,天气等信息。
<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>
1
2
3
4
5
6
7
8
9
10
首先给出我的前端代码,中括号内的变量就是我们下文中从高德地图返回给我们的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);
}
})
},
1
2
3
4
5
6
7
8
9
10
11
12
13
其实获取定位很简单,我们直接调用微信的接口wx.getLocation,结果会返回给我们一个json数组,结果就像上图一样,数组中包含各种属性,我们最需要的就是经度(longitude)和纬度(latitude),我们获得了当前位置的经纬度就可以调用高德地图的API,把我们的经纬度传上去,之后就能够获得高德地图给我们返回的信息。
首先我们需要从高德地图的官网上下载一个微信小程序SDK
http://lbs.amap.com/api/wx/download
在创建的项目中,新建一个名为 libs 目录,将 amap-wx.js (amap-wx.js 从下载的 zip 文件解压后得到)文件拷贝到 libs 的本地目录下,如下图所示。
接下来我们需要在页面的js文件中配置我们需要操作的数据
var amapFile = require('../../libs/amap-wx.js');
var markersData = {
latitude: '',//纬度
longitude: '',//经度
key: "需要去高德地图注册成为开发者,然后就会获得一个key"//申请的高德地图key
};
1
2
3
4
5
6
好了,我们配置好外部文件以后,就可以在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)
}
})
},
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
我们在onload函数中获取当前的定位,我们把经纬度信息传递给myAmapFun.getRegeo方法中的location参数,接下来我们可以看看高德地图给我们返回的信息。
我们获取了我们的位置以及邮政编码等一系列信息,大家可以去高德地图上注册一个开发者,得到一个key,然后测试一下,也可以获得你们当地的信息。
我们再看一下myAmapFun.getWeather给我们返回的天气信息。
---------------------