1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】国土地理院APIを使用して緯度・経度から都道府県を判定する

Posted at

概要

緯度・経度を元にどこの都道府県かを判定する方法はいくつか挙げられますが、無料で手軽にできる方法はないかと探していたところ、国土地理院APIなるものを見つけました。
今回は国土地理院APIを使用して、タイトルにある処理を実装してみたので紹介します。

実装方針や前提など

  • 国土地理院APIの詳細については、国土地理院APIでお手軽ジオコーディング&逆ジオコーディングの記事を参照ください。
  • 今回は緯度・経度から住所を判定するので、上記の記事で紹介されている逆ジオコーディングの機能を使用します。逆ジオコーディングで取得したコード(muniCd)を、muni.jsという変換表を使って都道府県コードを取得します。
  • 今回はTypeScriptで実装していますが、JavaScriptでも同様の内容で実装できると思います。

実装サンプル

緯度・経度を入力して、都道府県コードを取得する実装サンプルを以下に記載します。

export const useGeolocationService = () => {
  // 緯度・経度を項目として持つ型を受け取る
  const getPrefectureCodeFromLatLon = async (latLon: LatLon) => {
    const muniCd = await getMuniCdFromLatLon(latLon);
    if (!muniCd) {
      return undefined;
    }

    return getPrefectureCodeFromMuniCd(muniCd);
  };

  // 緯度・経度からmuniCdを取得
  const getMuniCdFromLatLon = async (latLon: LatLon) => {
    type LonLatToAddress = {
      results?: {
        muniCd: string;
        lv01Nm: string;
      };
    };

    const response = await fetch(
      `https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress?lat=${latLon.lat}&lon=${latLon.lon}`
    );
    if (!response.ok) {
      return undefined;
    }

    const lonLatToAddress: LonLatToAddress = await response.json();
    return lonLatToAddress.results?.muniCd;
  };

  // muniCdから都道府県コードを取得
  const getPrefectureCodeFromMuniCd = (muniCdInput: string) => {
    // 先頭が0の場合は除去
    const muniCd =
      muniCdInput.substring(0, 1) === "0" ? muniCdInput.slice(1) : muniCdInput;
    // muni.jsの一覧を元にしたリストから中身を取得
    const muniContents = MUNI_LIST.MUNI_ARRAY[muniCd];
    if (!muniContents) {
      return undefined;
    }

    // カンマ区切りの一番最初の値が都道府県コード
    return muniContents.split(",")[0];
  };

  return { getPrefectureCodeFromLatLon };
};
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?