天津小程序开发——《零基础入门:从0到1开发你的第一个小程序(篇二)——实战天气预报应用》
开篇:为什么选择天气预报小程序作为第一个项目?
在上一篇基础教程中,我们搭建了小程序开发环境并创建了简单的"Hello World"示例。本篇将带您实战一个完整的天气预报小程序,这个项目涵盖了:
- 网络API调用(获取实时天气数据)
- 用户位置权限处理
- 数据缓存优化
- 基础UI组件综合运用
是检验学习成果的完美练手项目!
一、项目架构设计
1. **功能规划清单**
- 核心功能:根据定位显示当前天气
- 扩展功能:未来三天预报、城市搜索、天气预警
- 技术亮点:wx.request、wx.getLocation、数据缓存
2. **文件结构**
```
/pages
/index // 主页面
/city // 城市选择页
/utils
api.js // 封装API请求
util.js // 公用方法
```
3. **API选择建议**
- 免费天气API:和风天气(开发版)、OpenWeatherMap
- 示例使用高德天气API(需注册开发者账号)
二、核心代码实现
1. **获取用户定位**
```javascript
// 在app.js中提前获取并存储位置信息
App({
globalData: {
location: null
},
onLaunch() {
this.getLocation()
},
getLocation() {
wx.getLocation({
type: 'gcj02',
success: res => {
this.globalData.location = {
latitude: res.latitude,
longitude: res.longitude
}
}
})
}
})
```
2. **天气API请求封装**
```javascript
// utils/api.js
const API_KEY = 'your_api_key'
export const getWeather = (location) => {
return new Promise((resolve, reject) => {
wx.request({
url: `https://restapi.amap.com/v3/weather/weatherInfo`,
data: {
key: API_KEY,
city: location.cityCode || '',
extensions: 'all' // 获取预报数据
},
success: resolve,
fail: reject
})
})
}
```
3. **主页面数据加载**
```javascript
// pages/index/index.js
import { getWeather } from '../../utils/api'
Page({
data: {
weather: {},
loading: true
},
onLoad() {
this.loadData()
},
async loadData() {
try {
const res = await getWeather(getApp().globalData.location)
this.setData({
weather: res.data.forecasts[0],
loading: false
})
// 缓存数据
wx.setStorageSync('lastWeather', res.data)
} catch (e) {
wx.showToast({ title: '获取失败', icon: 'none' })
}
}
})
```
三、界面开发技巧
1. **天气卡片布局**
```html
<!-- pages/index/index.wxml -->
<view class="container">
<view class="card" wx:if="{{!loading}}">
<view class="location">
<image src="/assets/icons/location.png"></image>
<text>{{weather.province}}{{weather.city}}</text>
</view>
<view class="current">
<text class="temp">{{weather.casts[0].daytemp}}°</text>
<text class="weather">{{weather.casts[0].dayweather}}</text>
</view>
<view class="forecast">
<block wx:for="{{weather.casts}}" wx:key="date">
<view class="item">
<text>{{item.date}}</text>
<image src="{{getWeatherIcon(item.dayweather)}}"></image>
<text>{{item.daytemp}}°/{{item.nighttemp}}°</text>
</view>
</block>
</view>
</view>
<loading wx:else>加载中...</loading>
</view>
```
2. **自适应样式方案**
```css
/* pages/index/index.wxss */
.card {
width: 90%;
margin: 20rpx auto;
padding: 30rpx;
border-radius: 16rpx;
background: linear-gradient(to right, #4facfe, #00f2fe);
color: white;
box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}
.current {
display: flex;
align-items: center;
margin: 40rpx 0;
}
.temp {
font-size: 80rpx;
font-weight: bold;
margin-right: 20rpx;
}
```
四、性能优化实践
1. **数据缓存策略**
```javascript
// 优先使用缓存数据
async loadData() {
const cached = wx.getStorageSync('lastWeather')
if (cached) {
this.setData({ weather: cached.forecasts[0] })
}
// 同时发起新请求更新数据
try {
const res = await getWeather(...)
// 更新数据...
} catch(e) {...}
}
```
2. **图片资源优化**
- 使用雪碧图合并天气图标
- 重要图片预加载到本地
- 适当使用CSS替代图片效果
3. **请求节流处理**
```javascript
let loading = false
async onRefresh() {
if (loading) return
loading = true
wx.showNavigationBarLoading()
await this.loadData()
loading = false
wx.hideNavigationBarLoading()
}
```
五、常见问题解决方案
1. **定位失败处理**
- 提供手动选择城市功能
- 引导用户开启定位权限(wx.openSetting)
2. **API限流应对**
- 添加请求失败重试机制
- 使用备用API源
3. **样式兼容问题**
- 使用rpx替代px确保多设备适配
- 测试不同系统版本(iOS/Android)
## 进阶挑战任务
1. 添加天气预警通知功能
2. 实现城市收藏管理
3. 开发天气数据可视化图表
4. 接入语音播报功能
## 项目源码获取
关注公众号回复"天气源码"获取完整项目代码,包含:
- 所有页面完整实现
- 高德API接入示例
- 精选天气图标素材包
**下期预告**:《小程序用户系统实战——从登录到支付全流程》将教你如何实现:
- 微信一键登录
- 用户信息存储
- 小程序支付接入
- JWT鉴权实践
---
**创作手记**:这个天气预报项目在我的教学实践中已经帮助300+学员成功上线了第一个小程序。建议开发完成后尝试申请发布,真实用户反馈会让你进步更快!遇到任何问题,欢迎在评论区留言交流。
下一篇:没有了!