API Keyを準備する
Address AutoComplete JavaScript専用のAPI Keyはありません。Address Search APIと同じAPI Keyと、同じ料金プラン・リクエスト上限を利用します。
API Keyの作成方法を確認し、Browser用途のAPI KeyにはHTTP Referer制限を設定してください。
Quick start
hosted scriptを読み込み、postcodejp.address.AutoComplementServiceへAddress Search API Keyを渡します。
<script src="https://postcode-jp.com/js/postcodejp.js"></script>
<script>
const service = new postcodejp.address.AutoComplementService("YOUR_API_KEY");
service.setZipTextbox("postcode");
service.add(new postcodejp.address.StateTextbox("prefecture"));
service.add(new postcodejp.address.TownTextbox("city"));
service.add(new postcodejp.address.StreetTextbox("address"));
service.observe();
</script>郵便番号inputはsetZipTextbox(idOrElement)、出力先はfield classを作成してadd()します。最後にobserve()を呼びます。
Output field classes
StateTextboxStateTownTextboxTownTextboxStreetTextboxTownStreetTextboxJigyosyoTextboxStateTownStreetTextboxStateSelectboxTownSelectbox
StateSelectboxとTownSelectboxはbyValue()またはbyText()でselect optionの照合方法を選べます。
Control methods
| Method | Purpose |
|---|---|
observe() | 郵便番号inputの監視を開始 |
stop() | event listenerを停止 |
restart() | 停止した監視を再開 |
getAddress() | 現在の郵便番号でmanual request |
setAutoComplement(false) | 自動補完を無効化 |
setComplementButton(...) | manual補完buttonを設定 |
enableOfficeAddress(boolean) | 事業所住所を対象にするか |
enableGeneralAddress(boolean) | 一般住所を対象にするか |
Options and callbacks
| API | Purpose |
|---|---|
setAdditionalFieldCallback(fn) | 追加field処理 |
setAdditionalCallback(fn) | 補完後の追加処理 |
setAlwaysCallback(fn) | 結果にかかわらず実行 |
setNotFoundCallback(fn) | 一致する住所がない場合 |
setClearAddressIfNotFound(true) | not found時に住所fieldをclear。default false |
setClearAddress(...) | clear対象を設定 |
setDumpResponse(true) | debug responseをconsoleへ出力 |
Input event contract
automatic補完は郵便番号inputのkeyupを監視します。programmaticにinput.valueを変更するだけではkeyupが発火せず、補完が始まりません。
programmatic update後に補完したい場合は、public method getAddress()を明示的に呼び出してください。
trim後の郵便番号が7文字または8文字のときrequestします。library自体はrequest前にNFKC変換やhyphen除去を行いません。
通信方式
Hosted JavaScriptはJSONP方式でAddress Search APIを利用し、API responseをscriptとして読み込みます。fetch/CORS方式と同じ通信ではありません。
CSPを設定しているサイトでは、https://postcode-jp.comとhttps://apis.postcode-jp.comからのscript読み込みを許可してください。
Authentication and security
Address Search API Keyと、そのkeyに設定されたplan/rate limitを使用します。JSONP requestではAPI Keyがrequest URLに含まれるため、browser用keyにはHTTP Referer制限を設定し、server-side secretを渡さないでください。
setDumpResponse(true)はdebug用途です。本番では無効にし、住所responseやrequest parameterをconsoleへ残さないでください。
Error handling
success/not-found callbackはありますが、network、認証、rate-limit errorを型付きで区別するcallback/eventは公開されていません。補完できない場合でもform入力を継続できるよう、fail-openなUIを用意してください。
導入後はPlaygroundと同様に、実際のkeyboard操作、not found、script load failure、page lifecycleを確認してください。