You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用OpenWeatherMap API结合循环批量获取多城市8天天气预报描述

解决OpenWeatherMap API多城市天气预报获取问题

嘿,我来帮你搞定这个函数的问题~先看看你现有代码里的几个小问题,再给你完整的解决方案:

首先修正基础错误

你定义的cities数组里的城市名没加引号,JS会把它们当作未定义的变量,必须改成字符串形式:

const cities = ['Cannes', 'London', 'Amsterdam', 'Berlin'];

核心问题:处理异步请求

$.ajax是异步操作,直接用普通for循环的话,会出现请求还没返回就继续执行后续代码的情况,所以我们需要用Promise.all来批量处理多个异步请求,确保所有城市的预报数据都拿到后再整理结果。

完整可运行代码示例

下面是结合OpenWeatherMap API的完整函数,我会标注每个关键部分:

async function getDescriptions() {
  // 修正后的城市列表
  const cities = ['Cannes', 'London', 'Amsterdam', 'Berlin'];
  // 替换成你自己的OpenWeatherMap API密钥(需要官网注册获取)
  const apiKey = 'YOUR_API_KEY';
  // 要获取的预报天数(注意免费版API的限制,后面会说明)
  const forecastDays = 8;

  // 为每个城市创建一个API请求的Promise
  const cityRequestPromises = cities.map(city => {
    return $.ajax({
      // 这里用每日预报API(需付费订阅,免费版看下面的替代方案)
      url: `https://api.openweathermap.org/data/2.5/forecast/daily`,
      data: {
        q: city, // 指定城市名
        appid: apiKey, // 你的API密钥
        cnt: forecastDays, // 请求未来N天的预报
        units: 'metric' // 可选:设置温度单位为摄氏度,换成imperial是华氏度
      },
      dataType: 'json'
    });
  });

  try {
    // 等待所有城市的请求完成,拿到所有预报数据
    const allForecastData = await Promise.all(cityRequestPromises);

    // 整理结果:提取每个城市的每日天气描述
    const result = allForecastData.map((forecast, index) => {
      const currentCity = cities[index];
      // 从每个预报的list数组中提取天气描述
      const dailyDescriptions = forecast.list.map(day => day.weather[0].description);
      return {
        city: currentCity,
        next8DaysDescriptions: dailyDescriptions
      };
    });

    // 输出结果,你也可以根据需求返回给其他逻辑使用
    console.log('各城市未来8天天气描述:', result);
    return result;
  } catch (error) {
    // 处理请求失败的情况
    console.error('获取天气预报出错:', error);
    throw error;
  }
}

// 调用函数
getDescriptions();

免费版API的替代方案

上面用的forecast/dailyAPI属于付费订阅项,如果你用的是免费版OpenWeatherMap账号,可以改用One Call API,不过免费版只能获取最多7天的每日预报。调整后的代码如下:

async function getDescriptions() {
  const cities = ['Cannes', 'London', 'Amsterdam', 'Berlin'];
  const apiKey = 'YOUR_API_KEY';

  // 为每个城市创建请求Promise,先通过地理编码API获取经纬度(One Call需要坐标)
  const cityRequestPromises = cities.map(async city => {
    // 第一步:获取城市的经纬度
    const geoResponse = await $.ajax({
      url: `https://api.openweathermap.org/geo/1.0/direct`,
      data: {
        q: city,
        limit: 1,
        appid: apiKey
      }
    });
    const { lat, lon } = geoResponse[0];

    // 第二步:用经纬度调用One Call API获取每日预报
    return $.ajax({
      url: `https://api.openweathermap.org/data/2.5/onecall`,
      data: {
        lat: lat,
        lon: lon,
        exclude: 'current,minutely,hourly,alerts', // 只保留每日预报数据
        appid: apiKey,
        units: 'metric'
      }
    });
  });

  try {
    const allForecastData = await Promise.all(cityRequestPromises);
    const result = allForecastData.map((forecast, index) => {
      const currentCity = cities[index];
      // 免费版daily数组包含7条数据(未来7天)
      const dailyDescriptions = forecast.daily.map(day => day.weather[0].description);
      return {
        city: currentCity,
        next7DaysDescriptions: dailyDescriptions
      };
    });
    console.log('各城市未来7天天气描述:', result);
    return result;
  } catch (error) {
    console.error('请求出错:', error);
    throw error;
  }
}

getDescriptions();

关键注意事项

  • 必须替换YOUR_API_KEY为你自己的OpenWeatherMap API密钥,你可以去OpenWeatherMap官网注册获取。
  • 免费版API有请求次数限制,不要频繁调用哦。
  • 如果你坚持要8天的预报,就需要升级到付费订阅的forecast/dailyAPI。

内容的提问来源于stack exchange,提问作者James Miller

火山引擎 最新活动