无法提取国家的城市OpenWeather。

问题描述 投票:1回答:1

我想在我的应用程序中使用Open-weather API。为此,我想我可能能够将城市和他们的ID保存在我自己的应用程序中的json文件中,每当我的用户想要一个地点的天气,应用程序从json中选择城市的ID并进行API调用。

为此,我下载了一个由Openweather提供的30MB的Json文件,它包含了所有的国家和所有的城市,将一个30MB的文件放在我的应用程序中显然不是一个好主意,所以我决定只提取我的国家的城市,但问题是,这个想法无法实现。如此多的城市从不同的国家有相同的名称,提取的json是巨大的,甚至一些城市代码是其他国家的城市。

我不知道是否有更好的实现方法,或者有什么想法或方法可以只提取一个国家的城市。

任何帮助实现天气呼叫在我的应用程序中的不同城市将被感激。

android ios react-native openweathermap
1个回答
0
投票

我知道这个问题是老问题了,但我最近也碰到了这个问题。我最后做的方法是将 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 包括国家名称,它们在数据中没有区别......

© www.soinside.com 2019 - 2024. All rights reserved.