📮

郵便番号から住所を補完するコード

2022/02/13に公開

概要

  • Webの申し込みフォームなどで郵便番号を入力すると住所が自動的に補完されるコードを書きます。
  • 無料の郵便番号API ポストくんを使いました。

調査

郵便番号から住所を呼び出すときには以下のようなURLで呼び出すだけです。

% curl -s https://postcode.teraren.com/postcodes/1600023.json | jq
{
  "postcode_type": "area",
  "jis": "13104",
  "old": "160",
  "new": "1600023",
  "prefecture_kana": "トウキョウト",
  "city_kana": "シンジュクク",
  "suburb_kana": "ニシシンジュク",
  "prefecture": "東京都",
  "city": "新宿区",
  "suburb": "西新宿",
  "street_address": null,
  "office": null,
  "office_kana": null,
  "post_type": null,
  "is_separated_suburb": 0,
  "is_koaza": 0,
  "is_chome": 1,
  "is_include_area": 0,
  "status": 0,
  "reason": 0,
  "created_at": "2023-02-08T05:10:49.000Z",
  "updated_at": "2023-02-08T05:10:49.000Z"
}

実装

上記を踏まえてコードを書きます。とても簡単です。

HTML

HTML側は郵便番号の入力フォームと、取得したデータを表示する部分を作っておきます。

<form>
  <div>
    <h2>郵便番号入力</h2>
  <input type="text" id="postcode" placeholder="1600023" maxlength="7" autofocus>
  </div>
  <div>
    <h2>住所補完</h2>
  <input type="text" id="prefecture" placeholder="東京都" disabled>
  <input type="text" id="city" placeholder="新宿区" disabled>
  <input type="text" id="suburb" placeholder="西新宿" disabled>
  </div>
</form>

JavaScript

キーボードの入力が行われて数字が7桁だったらAPIで問い合わせをしています。

document.addEventListener('keyup', function(e) {
  if (!(48 <= e.keyCode && e.keyCode <= 57)) { // 0 - 9
    return;
  }

  const postcode = document.getElementById('postcode').value;
  
   if (postcode.length != 7) {
     return;
   }

  const url = "https://postcode.teraren.com/postcodes/" + postcode + ".json";
  fetch(url)
    .then(response => response.json())
    .then((json) => {
      document.getElementById('prefecture').value = json.prefecture;
      document.getElementById('city').value = json.city;
      document.getElementById('suburb').value = json.suburb;
    })
    .catch(error => {
      document.getElementById('prefecture').value = '';
      document.getElementById('city').value = '';
      document.getElementById('suburb').value = '';
    });

});

デモはこちら

https://codepen.io/matsubokkuri/pen/XWPrNNw

Discussion