nativescript-weather-api
地球任何地点的实时天气信息,包括超过20万个城市。
npm i --save nativescript-weather-api

NativeScript 天气 API

地球任何地点的实时天气信息,包括超过20万个城市。

安装

tns plugin add nativescript-weather-api

权限

Android

为了请求访问位置,您需要将以下行添加到您的应用的 AndroidManifest.xml 中

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

iOS

您需要在 Info.plist 中包含 NSLocationWhenInUseUsageDescription 键来启用使用应用时的地理位置。

用法

此插件使用 OpenWeather API 显示天气信息,因此您需要在 https://openweathermap.org 上创建账户并获取您的密钥。免费账户每月可执行1000万次调用和每分钟60次调用。

导入插件

import { getWeather, dailyForecast, showWeather, getLocation } from 'nativescript-weather-api';

API 调用

通过地理坐标

当使用坐标时,您不能传递城市和ZIP代码参数。

var temp;
var wind;

getLocation().then((location) => {

getWeather({

key: "your_key",
lat: location.latitude,
lon: location.longitude,
unit: "metric"

}).then(() => {

var data = new showWeather();
temp = data.temp;
wind = data.wind;
});

});

通过城市名称

当通过城市名称调用时,您不能传递纬度、经度和ZIP代码参数。

var temp;
var wind;

getWeather({

key: "your_key",
city: "London",
country: "GB"

}).then(() => {

var data = new showWeather();
temp = data.temp;
wind = data.wind;
});

通过ZIP代码

此方法似乎不适用于所有国家。例如,在我的测试中,API 没有识别出巴西的ZIP代码。

不要传递纬度、经度和城市参数。

var temp;
var wind;

getWeather({

key: "your_key",
zip_code: "90001",
country: "US"

}).then(() => {

var data = new showWeather();
temp = data.temp;
wind = data.wind;
});

参数

key - 您的 OpenWeather 密钥。
lat - 纬度。
lon - 经度。
city - 城市名称,例如,洛杉矶。
country - 国家代码,例如,US,CA,GB。
zip_code - 数字或字母数字代码,例如,90001。
unit - 如果您将其设置为 metric,则温度将转换为摄氏度,风速以米/秒为单位。如果您选择 imperial,则温度将转换为华氏度,风速以英里/小时为单位。如果您不设置此参数,则默认为开尔文和米/秒。
lang - 城市名称和描述字段的输出语言,例如,en,pt_br,fr,es。

标识符

name - 位置名称。
country - 国家名称。
temp - 温度。
temp_min - 最小温度。
temp_max - 最大温度。
feels_like - 体感温度。
wind - 风速。
pressure - 压力。
humidity - 湿度。
description - 天气描述,例如,晴朗的天空。
icon - 天气图标URL。

7天的每日预报

只需一个调用,您就可以获取7天加当天的天气信息。

var temp_min;
var temp_max;
var description;

getLocation().then((location) => {

dailyForecast({

key: "your_key",
lat: location.latitude,
lon: location.longitude,
unit: "metric"

}).then((data) => {

temp_min = data.daily[0].temp.min;
temp_max = data.daily[0].temp.max;
description = data.daily[0].weather[0].description;
});

});

dailyForecast 函数只接受纬度和经度来确定位置。在示例中,我们检索了当天最低和最高温度以及天气描述。如果我们想要获取下一天的信息,我们将 daily[0] 改为 daily[1],依此类推,直到 daily[7]。要查看除本节中使用的字段之外的所有可用字段,请创建 alert(JSON.stringify(data, null, 4)),但在构建生产版本之前不要忘记删除它。

NS 兼容性

将您的 NS 版本更新到 8+,否则您可能会遇到 @nativescript/geolocation 插件错误。