1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

気象庁APIからエリアコードを取得する

Posted at

気象庁のエリアコードを取得と検索をするコード

interface AreaInfo {
  name: string;
  enName: string;
  officeName?: string;
  kana?: string;
  parent: string;
  children?: string[];
}

interface AreaCodeData {
  centers?: { [key: string]: AreaInfo };
  offices?: { [key: string]: AreaInfo };
  class10s?: { [key: string]: AreaInfo };
  class15s?: { [key: string]: AreaInfo };
  class20s?: { [key: string]: AreaInfo };
  [key: string]: any;
}

export async function getAreaCode(): Promise<AreaCodeData> {
  const AREA_CODE_JSON_URL = "https://www.jma.go.jp/bosai/common/const/area.json"
  const response = await fetch(AREA_CODE_JSON_URL);
  const json = await response.json();

  return json;
}

export async function searchByName(name: string): Promise<{ code: string; info: AreaInfo }[]> {
  const data = await getAreaCode();
  const results: { code: string; info: AreaInfo }[] = [];

  // centers, offices, class10s などすべてのカテゴリを検索
  for (const category of Object.values(data)) {
    if (typeof category === 'object' && category !== null) {
      for (const [code, info] of Object.entries(category)) {
        if (info && typeof info === 'object' && 'name' in info && info.name === name) {
          results.push({ code, info: info as AreaInfo });
        }
      }
    }
  }

  return results;
}

const data = await searchByName('東京都');
console.log(data);

東京都の結果

[
  {
    code: '130000',
    info: {
      name: '東京都',
      enName: 'Tokyo',
      officeName: '気象庁',
      parent: '010300',
      children: [Array]
    }
  }
]

府中市にすると以下のようになる

[
  {
    code: '1320600',
    info: {
      name: '府中市',
      enName: 'Fuchu City',
      kana: 'ふちゅうし',
      parent: '130013'
    }
  },
  {
    code: '3420800',
    info: {
      name: '府中市',
      enName: 'Fuchu City',
      kana: 'ふちゅうし',
      parent: '340012'
    }
  }
]
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?