はじめに
今回は、郵便番号を入力することにより住所を取得するプログラムを紹介します。
今回は「ポストくん」の提供するAPIを利用したものになります。
このプログラムを使用することでJavaScript単体でAPIに問い合わせて郵便番号から住所を取得することができます。
コード作成
入力・表示部作成
郵便番号入力と住所を表示するHTMLを作成します。入力フォームに似せて作成したかったので、都道府県はドロップダウンから選択、住所はテキストボックスを採用しました。
郵便番号はハイフンの有無どちらも対応することとしたため8桁まで入力が可能です。
<!DOCTYPE html>
<head>
<title>住所検索</title>
<style>
label {
display: inline-block;
width: 7em;
vertical-align: top;
}
</style>
<script src="searchZipcode.js"></script>
</head>
<body>
<label for="zipCode">郵便番号:</label>
<input type="text" id="zipCode" maxlength="8" />
<input type="button" id="submit" value="住所取得" onClick="addressSearch()" />
<hr />
<label for="prefectures">都道府県:</label>
<select id="prefectures"></select><br />
<label for="city">市区町村:</label>
<input type="text" id="city" /><br />
</body>
</html>ドロップダウン選択生成
都道府県のドロップダウンの選択肢を生成する部分を作成します。初めから選択できる必要があるのでonloadを用いてページ表示時にドロップダウンの選択肢を作成します。
都道府県は配列のインデックスがそのまま使用できるようにJIS規格の順番にしています。
window.onload = () => {
addPrefectureOption();
};
const addPrefectureOption = () => {
const prefectures = [
'北海道', '青森県', '岩手県', '宮城県', '秋田県', '山形県', '福島県', '茨城県',
'栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県', '新潟県', '富山県',
'石川県', '福井県', '山梨県', '長野県', '岐阜県', '静岡県', '愛知県', '三重県',
'滋賀県', '京都府', '大阪府', '兵庫県', '奈良県', '和歌山県', '鳥取県', '島根県',
'岡山県', '広島県', '山口県', '徳島県', '香川県', '愛媛県', '高知県', '福岡県',
'佐賀県', '長崎県', '熊本県', '大分県', '宮崎県', '鹿児島県', '沖縄県',
];
const select = document.getElementById('prefectures');
// 初期値を選択肢に追加
const option = document.createElement("option");
option.text = `--選択--`;
option.value = null;
option.selected = true;
option.disabled = true;
select.appendChild(option);
// 都道府県を選択肢に追加
prefectures.forEach((pref, idx) => {
const option = document.createElement('option');
option.text = pref;
option.value = idx + 1;
select.appendChild(option);
});
}住所取得処理
郵便番号から住所を取得する箇所を作成します。郵便番号はハイフンの有無を考慮するため、どちらの場合でも7桁の数値となるようにしています。APIから取得でき情報には、住所カナやローマ字も含まれていますので使用用途によって取得項目を選択することも可能です。
const addressSearch = () => {
// エレメント情報取得
const zipCode = document.getElementById('zipCode');
const prefSelect = document.getElementById('prefectures');
const city = document.getElementById('city');
// 初期化処理
prefSelect.value = null;
city.value = '';
// 郵便番号取得
const code = zipCode.value.replace(/[^0-9]/g, '');
// 郵便番号桁数確認
if (!code.match(/\d{7}/)) {
alert('郵便番号の入力に誤りがあります');
return;
}
// API取得
const url = `https://postcode.teraren.com/postcodes/${code}.json`;
fetch(url)
.then(response => response.json())
.then((json) => {
// 取得住所挿入
prefSelect.value = json.jis.substr(0, 2);
city.value = json.city + json.suburb;
})
.catch(() => {
window.alert('住所が存在しませんでした。');
});
}以上でAPIより郵便番号から住所が取得できます。
動作イメージ
注意点
以下に挙げる郵便番号は、複数都道府県にまたがるため正常な住所を取得できない可能性があります。
(作成時点で確認したところAPIからは1番目の住所が取得されました。)
- 〒498-0000・・・愛知県弥富市 / 三重県桑名市木曽岬町
- 〒618-0000・・・京都府乙訓郡大山崎町 / 大阪府三島郡島本町
- 〒871-0000・・・福岡県築上郡吉富町 / 大分県中津市
郵便番号の仕様のため回避は困難です。ただし、上記の郵便番号の出現度合いは非常に低いためひとまずは問題ないと判断しました。
必要があれば、特例となる郵便番号の際はモーダルなどで選択肢を提示しても良いかもしれません。



コメント