【问题标题】:Can't extract cities of country OpenWeather无法提取国家/地区的城市 OpenWeather
【发布时间】:2019-08-05 03:36:30
【问题描述】:

我想为我的应用程序使用开放天气 API。为此,我认为我可以将城市及其 ID 保存在我自己的应用程序中的 json 文件中,并且每当我用户想要位置天气时,应用程序从 json 中选择城市 ID 并进行 API 调用。

为此,我下载了 Openweather 提供的 30MB Json 文件,其中包含所有国家和所有城市。在我的应用程序中放置 30MB 显然不是一个好主意。所以我决定只提取我的乡村城市。但关键是,这个想法无法实现。这么多来自不同国家的城市有相同的名字。并且提取的 json 再次变得巨大。甚至一些国家代码是其他国家的城市。

我想知道是否有更好的实现方式。或任何想法或方法来提取一个国家的城市。

任何帮助在我的应用中为不同城市实施天气呼叫的任何帮助都将不胜感激

【问题讨论】:

    标签: android ios react-native openweathermap


    【解决方案1】:

    我知道这个问题很老,但我最近也遇到了这个问题。我最终这样做的方式是将city.list.json 设置为默认导出的 JSON 对象并编写节点脚本,然后按国家代码删除城市:

    var fs = require('fs');
    var cityList = require('./city.list.js');
    
    let output = {};
    let countryCodes = [];
    
    cityList.forEach((city) => {
      const country = city.country;
      if (country) {
        if (!countryCodes.includes(country)) {
          countryCodes.push(country);
        }
        if (!output[country]) {
          output[country] = [];
        }
        output[country].push({
          id: city.id,
          name: city.name,
        });
      }
    });
    
    for (const [key, value] of Object.entries(output)) {
      const fileName = 'city.' + key.toLowerCase() + '.json';
      fs.writeFile(fileName, JSON.stringify(value), function (err) {
        if (err) console.error(err.message);
        console.log(fileName + ' - saved!');
      });
    }
    
    fs.writeFile('countrycodes.json', JSON.stringify(countryCodes), function (err) {
      if (err) console.error(err.message);
      console.log('countrycodes.json' + ' - saved!');
    });
    

    这完全有效!然后我遇到的唯一问题是city.list.json 包含国家名称,并且它们在数据中没有区别......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 2011-10-12
      • 2012-03-29
      • 2017-09-02
      • 2015-11-18
      • 2017-06-30
      • 1970-01-01
      相关资源
      最近更新 更多