387 文字
2 分
郵便番号から住所を補完するコード
概要
- 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(ES6)
キーボードの入力が行われて数字が7桁だったらAPIで問い合わせをしています。
document.addEventListener('keyup', (e) => { // 0 - 9 の数字キーでない場合は処理を終了 if (!(e.keyCode >= 48 && e.keyCode <= 57)) return;
const postcode = document.getElementById('postcode').value;
// 郵便番号が7桁でない場合は処理を終了 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://blog.teraren.com/posts/qiita-20230213-30f724b296d1b0729503/ 関連記事
この記事が役に立ったら
GitHub Sponsorsで応援できます