鸿蒙原生开发手记:徒步迹 - 天气卡片组件开发
·

鸿蒙原生开发手记:徒步迹 - 天气卡片组件开发
集成天气数据,打造实用的首页天气卡片
一、前言
天气信息对户外徒步非常重要。本文实现一个天气卡片组件,展示当前位置的天气状况,包括温度、天气图标、空气质量等。
二、天气数据模型
interface WeatherData {
temperature: number; // 当前温度(°C)
high: number; // 最高温
low: number; // 最低温
condition: string; // 天气状况(晴/多云/雨等)
icon: string; // 天气图标
humidity: number; // 湿度(%)
windSpeed: number; // 风速(km/h)
aqi: number; // 空气质量指数
aqiLevel: string; // 空气质量等级
}
三、天气卡片组件
@Component
struct WeatherCard {
@Prop weather: WeatherData = {
temperature: 22,
high: 26,
low: 18,
condition: '晴',
icon: '☀️',
humidity: 45,
windSpeed: 15,
aqi: 55,
aqiLevel: '良',
};
build() {
Row() {
// 左侧:温度 + 天气图标
Column() {
Text(this.weather.icon)
.fontSize(40);
Text(`${this.weather.temperature}°C`)
.fontSize(28)
.fontWeight(FontWeight.Bold);
Text(this.weather.condition)
.fontSize(14)
.fontColor('#666');
}
.alignItems(HorizontalAlign.Center);
// 右侧:详细信息
Column() {
Text(`${this.weather.high}° / ${this.weather.low}°`)
.fontSize(16);
Row() {
this.InfoChip('💧', `${this.weather.humidity}%`);
this.InfoChip('💨', `${this.weather.windSpeed}km/h`);
this.InfoChip('🌬️', this.weather.aqiLevel);
}
.margin({ top: 8 });
}
.layoutWeight(1)
.alignItems(HorizontalAlign.End);
}
.width('100%')
.padding(16)
.backgroundColor('#E3F2FD')
.borderRadius(16);
}
@Builder
InfoChip(icon: string, text: string) {
Row() {
Text(icon).fontSize(12);
Text(text).fontSize(12).fontColor('#666').margin({ left: 3 });
}
.padding({ left: 8, right: 8, top: 4, bottom: 4 })
.backgroundColor('rgba(255,255,255,0.6)')
.borderRadius(12)
.margin({ left: 4 });
}
}
四、获取天气数据
async function fetchWeather(lat: number, lng: number): Promise<WeatherData> {
// 调用天气 API
const response = await apiService.request('/api/weather', 'GET', {
lat, lng,
});
if (response.code === 200) {
return response.data as WeatherData;
}
// 返回默认数据
return {
temperature: 22,
high: 26, low: 18,
condition: '晴', icon: '☀️',
humidity: 45, windSpeed: 15,
aqi: 55, aqiLevel: '良',
};
}
五、集成到首页
在首页的 aboutToAppear 中加载天气数据:
aboutToAppear(): void {
this.loadWeather();
}
async loadWeather(): Promise<void> {
try {
const weather = await fetchWeather(39.908, 116.397);
AppStorage.setOrCreate('currentWeather', weather);
} catch (e) {
console.error('加载天气失败');
}
}
六、总结
天气卡片是徒步 App 首页的重要组件,为用户提供出行决策参考。通过组件化设计,WeatherCard 可以灵活复用。
下一篇文章将实现路线列表页,使用 @LazyForEach 优化长列表性能。
下一篇预告:鸿蒙原生开发手记:徒步迹 - 路线列表页与@LazyForEach
更多推荐




所有评论(0)