在OpenHarmony地图上获取实时天气信息,需通过地图定位获取坐标→调用天气API获取数据→将天气信息与地图标记/卡片关联三个核心步骤实现。以下是具体实现方案:
选择专业气象数据平台的开放接口(如和风天气、OpenWeatherMap、高德地图天气API),注册开发者账号并创建项目,获取API密钥(用于身份验证)。确保接口权限包含“实时天气查询”(如和风天气的now接口、高德地图的weatherInfo接口)。
OpenHarmony地图组件(如@ohos.map.element.Element、@ohos.map.service.LocationService)可获取当前地图中心点或标记点的经纬度(latitude、longitude),这是调用天气API的必要参数。
示例代码(获取当前地图中心点经纬度):
import map from '@ohos.map.element.Element';
// 获取地图实例
let mapInstance = map.getMapInstance();
// 监听地图中心点变化(实时获取)
mapInstance.on('centerchanged', (event) => {
let center = event.center; // 地图中心点坐标
let latitude = center.latitude;
let longitude = center.longitude;
console.log(`当前中心点经纬度:${latitude}, ${longitude}`);
});
使用OpenHarmony的网络请求模块(如http模块、axios第三方库),向天气API发送GET请求,传入经纬度及API密钥,获取实时天气数据(如温度、湿度、风向、天气描述等)。
http模块(适用于简单请求):import http from '@ohos.net.http';
import { parse } from '@ohos.util.json';
async function fetchRealTimeWeather(latitude: number, longitude: number, apiKey: string) {
let baseUrl = `https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${latitude},${longitude}`;
let request = http.createHTTPRequest();
let options = {
method: http.RequestMethod.GET,
header: { 'Content-Type': 'application/json' }
};
try {
let response = await request.request(baseUrl, options);
if (response.responseCode === 200) {
let weatherData = parse(response.result.toString());
console.log('实时天气数据:', weatherData);
return weatherData; // 返回解析后的JSON数据
}
} catch (error) {
console.error('获取天气数据失败:', error);
}
}
axios第三方库(简化请求逻辑,需通过ohpm安装):import axios from '@ohos/axios';
async function fetchRealTimeWeather(latitude: number, longitude: number, apiKey: string) {
let baseUrl = `https://api.weatherapi.com/v1/current.json`;
try {
let response = await axios.get(baseUrl, {
params: { key: apiKey, q: `${latitude},${longitude}` }
});
console.log('实时天气数据:', response.data);
return response.data; // 返回解析后的JSON数据
} catch (error) {
console.error('获取天气数据失败:', error);
}
}
获取天气数据后,可通过以下两种方式在地图上展示:
地图标记(Marker)添加天气图标与信息
在地图标记的infoWindow(信息窗口)中,显示实时天气的关键信息(如温度、天气描述),并通过setIcon方法设置天气图标(如晴天、雨天图标)。
示例代码:
import map from '@ohos.map.element.Element';
import { Resource } from '@ohos.resourceManager';
// 假设已获取天气数据(weatherData)
let marker = {
id: 'weather_marker',
position: { latitude: latitude, longitude: longitude },
icon: getWeatherIcon(weatherData.current.condition.code), // 根据天气代码获取图标资源
title: '实时天气',
infoWindow: {
content: `温度:${weatherData.current.temp}°C\n天气:${weatherData.current.condition.text}`,
visible: true
}
};
// 添加标记到地图
mapInstance.addMarker(marker);
(注:getWeatherIcon为自定义函数,需根据天气代码映射对应图标资源,如1000=晴天、1003=多云)。
服务卡片(Form)展示动态天气
通过OpenHarmony的原子化服务卡片(FormAbility+ArkTS),将实时天气数据以卡片形式叠加在地图上,支持动态更新(如实时刷新温度、天气图标)。
示例代码(卡片数据绑定):
@Entry
@Component
struct WeatherCard {
@State temp: string = '';
@State condition: string = '';
aboutToAppear() {
// 调用天气API获取数据
fetchRealTimeWeather(39.9042, 116.4074, 'your_api_key').then(data => {
this.temp = `${data.current.temp}°C`;
this.condition = data.current.condition.text;
});
}
build() {
Column() {
Text(this.temp).fontSize(24).fontWeight(FontWeight.Bold);
Image($r('app.media.weather_icon')) // 根据天气代码设置图标
.width(80).height(80);
Text(this.condition).fontSize(18).fontColor('#666');
}
.width('100%').height('100%').padding(16)
}
}
(注:需在form_config.json中配置卡片的updateEnabled为true,支持定时或手动刷新)。
module.json5中添加网络权限,确保应用能访问互联网:"requestPermissions": [
{ "name": "ohos.permission.INTERNET" }
]
@ohos.data.preferences模块缓存天气数据(如缓存15分钟),当用户再次打开地图时,优先展示缓存数据,再异步更新。通过以上步骤,即可在OpenHarmony地图上实现实时天气信息的获取与展示,提升地图的实用性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。