开发一个现实天气信息的微信小程序,主要的是从网上请求到天气信息数据,网上也有很多介绍免费天气api接口的,我试了好多没法用,或者就是像百度api一样弄了半天没搞明白,我这里使用了高德和“天气API”提供的两种天气api接口。
一、使用高德天气接口:
网址链接为:
https://lbs.amap.com/api/webservice/guide/api/weatherinfo
(一)注册并获取Key
使用时候需要注册获取Key,因为是阿里旗下公司,可以使用支付宝扫码注册。注册后在图中所示的页面中点击 申请Key:

在打开的页面中点击右上角的“创建新应用”,填写应用名称和类型,我这里随便把应用名称定为Weather,创建好之后点击“添加”

可以给Key添加名字,服务平台注意要选择 Web服务,这个选项才能使用天气查询API(这里不需要再点击它了)

提交之后就可以找到申请的Key了,这时候就可以去使用API了。
(二)调用API接口
新建项目后,在index.js(或者新建一个页面)中加入以下代码:
//index.js //获取应用实例 const app = getApp() Page({
data: {
}, onLoad:function(){
var self = this; wx.request({
url: 'https://restapi.amap.com/v3/weather/weatherInfo', data:{
'key': '*',//填入自己申请到的Key 'city': '', }, header:{
'content-type': 'application/json' }, success:function(res){
console.log(res.data); } }) } })
index.wxml
<!--index.wxml--> <view class="content"> <view class="info"> 城市编码:{
{
adcode}}</view> <view class="info"> 所在省份:{
{
province}}</view> <view class="info"> 城市:{
{
city}}</view> <view class="info">天气现象:{
{
weather}}</view> <view class="info"> 实时气温:{
{
temperature}}℃</view> <view class="info"> 风向:{
{
winddirection}}</view> <view class="info"> 风力:{
{
windpower}}</view> <view class="info"> 空气湿度:{
{
humidity}}%</view> <view class="info"> 发布时间:{
{
reporttime}}</view> </view>
index.js
//index.js //这里只获取了实况天气信息,没有用预测信息 //获取应用实例 const app = getApp() Page({
data: {
adcode:'', city:'', humidity:'', province:'', reporttime:'', temperature:'', weather:'', winddirection:'', windpower:'', }, onLoad:function(){
var self = this; wx.request({
url: 'https://restapi.amap.com/v3/weather/weatherInfo', data:{
'key': '*',//改为自己申请的Key 'city': '', 'extensions': 'base' }, header:{
'content-type': 'application/json' }, success:function(res){
console.log(res.data); self.setData({
adcode: res.data.lives[0].adcode, city: res.data.lives[0].city, humidity: res.data.lives[0].humidity, province: res.data.lives[0].province, temperature: res.data.lives[0].temperature, reporttime: res.data.lives[0].reporttime, weather: res.data.lives[0].weather, winddirection: res.data.lives[0].winddirection, windpower: res.data.lives[0].windpower }) } }) } })
二、使用“天气API”提供的接口
(一)注册获取APPID和APPSecret
(二)调用API接口
//index.js //获取应用实例 const app = getApp() Page({
data: {
}, onLoad:function(){
var self = this; wx.request({
//根据自己申请到的appid和appsecret替换下面的*符号 url: 'https://v0.yiketianqi.com/api?version=v61&appid=&appsecret=*', data:{
}, header:{
'content-type': 'application/json' }, success:function(res){
console.log(res.data); } }) } })
//index.js //获取应用实例 const app = getApp() Page({
data: {
}, onLoad:function(){
var self = this; wx.request({
url: 'https://v0.yiketianqi.com/api', data:{
'appid':'',//填入自己申请到的appid 'appsecret': '',//填入自己申请到的appsecret 'version': 'v61' }, header:{
'content-type': 'application/json' }, success:function(res){
console.log(res.data); } }) } })
可以得到和上面同样的结果。根据该网站提供所提供的不同接口,可以尝试不同的version,得到不同的信息。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/178852.html原文链接:https://javaforall.net
