文書更新:2019年06月27日(木) 午前9時40分18秒

Home > その他 > 郵便番号 > JavaScript の利用 > IW3 PROJECT の API を使用( 181 )

IW3 PROJECTのAPIを使用して作ってみました。

郵便番号から住所を検索

コード

  1. Script部
  2. <SCRIPT LANGUAGE="JavaScript">
    var ZipCode = function(zip){	//クラス ZipCode の定義
    	if(!zip){	//Nullの場合
    		this.status=false;
    		this.error_msg="郵便番号が入力されていません。";
    		alert(this.error_msg);
    		return;
    	}else if(zip.match(/^\d{7}$/)){	//ハイフォンなしの7桁番号
    		this.zip_code=zip.replace(/^([0-9]{3})([0-9]{4})$/,"$1-$2");
    		this.status=true;
    	}else if(zip.match(/^([0-9]{3})-([0-9]{4})$/)){	//ハイフォン付きの7桁番号
    		this.zip_code=zip;
    		this.status=true;
    	}else{
    		this.status=false;
    		this.error_msg="郵便番号 [ "+zip+" ] が正しくありません。";
    		alert(this.error_msg);
    		return;
    	}
    	//******************
    	this.GetErrorMsg=function(){
    		return this.error_msg;
    	}
    	this.GetStatus=function(){
    		return this.status;
    	}
    	this.GetZipCode=function(){
    		return this.zip_code;
    	}
    	if(this.status){	//住所検索
    		var zip=this.zip_code.replace("-","/");	//ハイフォンなしの7桁番号に直す
    		RemoveScript('//api.thni.net/jzip/');
    		var target=document.createElement("script");
    		target.src = "//api.thni.net/jzip/"+zip+".json";	//IW3 PROJECTのサイトから住所情報を取得
    		document.body.appendChild(target);
    	}
    }
    function SearchAddress(){	//検索ボタンが押された時に呼ばれる関数
    	var zipcode=document.getElementById("zip").value;
    	var obj=new ZipCode(zipcode);	//クラス ZipCode をコールし住所情報を取得する
    }
    function ZipSearchValue(zip){	//コールバック関数(住所情報の取得)
    	document.getElementById("pref").value=zip.stateName;
    	document.getElementById("city").value=zip.city;
    	document.getElementById("town").value=zip.street;
    }
    function Ctrl_cursor(ctrl){	//マウスカーソルの制御
    	document.body.style.cursor = ctrl;
    	var tag=Array('input','a','button','select');
    	for(var j=0;j<tag.length;j++){
    		for (var i = 0; i < document.getElementsByTagName(tag[j]).length; i++) {
    			document.getElementsByTagName(tag[j])[i].style.cursor = ctrl;
    		}
    	}
    }
    function RemoveScript(url){
    	for(var i=document.scripts.length-1;i>=0;i--){
    		var p=document.getElementsByTagName('script')[i];
    		if(p.getAttribute('src')!=null&&p.getAttribute('src').indexOf(url)==0){
    			p.parentNode.removeChild(p);
    		}
    	}
    }
    </SCRIPT>

  3. Html部
  4. <div style="text-align:left;padding-left:10px;">
    <form>
    <table>
    <tr><th>郵便番号:</th><td><input type="text" id="zip" size="8" maxlength="7"><input type="button" onclick="SearchAddress();return false;" value="住所検索"> ※ハイフォンなしで入力してください。</td></tr>
    <tr><th>都道府県:</th><td><input type="text" id="pref" size="8"></td></tr>
    <tr><th>市区町村:</th><td><input type="text" id="city" size="30"></td></tr>
    <tr><th>町域:</th><td><input type="text" id="town" size="30"></td></tr>
    </table>
    </form>
    </div>