文書更新:2018年08月29日(水) 午前9時32分52秒

Home > その他 > 郵便番号 > JavaScript の利用 > zip.cgis.biz の API を使用( 179 )

zip.cgis.bizのAPIを使用して作ってみました。

郵便番号から住所を検索

コード

  1. ローカルファイルのphp部(zip.cgis.biz.php)
  2. 直接zip.cgis.bizからXMLデータを取得しjsonに変換しています。また、callback関数を設定できるようにした。
    if(preg_match('/zn=(\d{7})/',$_SERVER["QUERY_STRING"],$ret)&&!preg_match('/zn=(\d{8})/',$_SERVER["QUERY_STRING"])){
    		$zip=$ret[1];
    		$data = simplexml_load_file("http://zip.cgis.biz/xml/zip.php?zn={$zip}");
    		$json = json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
    		$json=preg_replace("/none/", "", $json);
    	}else{
    		$json="";
    	}
    	if($_GET["callback"]==""){
    		$callback="GetZipInfo";
    	}else{
    		$callback=$_GET["callback"];
    	}
    	header("Content-type: text/javascript;");
    	echo $callback."(";
    	echo $json;
    	echo ");";
  3. javascript部
  4. 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(){		//郵便番号の状態sを取得
    		return this.status;
    	}
    	this.GetZipCode=function(){		//ハイフォン付き7桁番号の取得
    		return this.zip_code;
    	}
    	if(this.status){	//住所検索
    		Ctrl_cursor("wait");	//マウスカーソルを待機状態にする
    		var zip=this.zip_code.replace("-","");	//ハイフォンなしの7桁番号に直す
    		RemoveScript("//leom.mydns.jp/php/zip.cgis.biz.php/");
    		var target=document.createElement("script");
    		target.src = "//leom.mydns.jp/php/zip.cgis.biz.php/?zn="+zip+"&callback=GetAddress";	//ricollabのサイトから住所情報を取得
    		document.body.appendChild(target);
    
    	}
    }
    function SearchAddress(){	//検索ボタンが押された時に呼ばれる関数
    	var zipcode=document.getElementById("zip").value;
    	var obj=new ZipCode(zipcode);	//クラス ZipCode をコールし住所情報を取得する
    }
    var g_zip;
    function GetAddress(zip){	//コールバック関数(住所情報の取得)
    	Ctrl_cursor("default");	//マウスカーソルを元に戻す
    	if(zip.result[8]["@attributes"].result_values_count==0){
    		alert('該当する郵便番号が見つかりません');
    	}else if(zip.result[8]["@attributes"].result_values_count==1){
    		if(zip.ADDRESS_value.value[3]["@attributes"].company_kana==""){
    			ViewForm(true);
    			document.getElementById("zip").value=zip.result[3]["@attributes"].request_zip_num;
    			SetZipDataSub(zip.ADDRESS_value);
    		}else{
    			ViewForm(false);
    			document.getElementById("zip").value=zip.result[3]["@attributes"].request_zip_num;
    			SetZipDataSub(zip.ADDRESS_value);
    			document.getElementById("office").value=zip.ADDRESS_value.value[7]["@attributes"].company;
    			document.getElementById("office_kana").value=zip.ADDRESS_value.value[3]["@attributes"].company_kana;
    		}
    	}else{
    		g_zip=zip;
    		OpenMiniWindow(zip);
    	}
    }
    function OpenMiniWindow(zip){
    	var url=""; //ウィンドウに表示するURL
    	var x_width=600;    //ウィンドウの横幅
    	var y_height=150;   //ウィンドウの高さ
    	var x_pos=Number((window.screen.width-x_width)/2);
    	var y_pos=Number((window.screen.height-y_height)/2);
    	win=window.open(url,"zipcode","width="+x_width+",height="+y_height+",left="+x_pos+",top="+y_pos+",location=no,menubar=no,toolbar=no,resizable=yes,scrollbars=yes");
    	var ret='※左側の「利用する」ボタンをクリックしてください。';
    	ret+='<table class="zipcode" cellspacing="0" cellpadding="0" border="0">';
    	ret+='<tbody style="white-space:pre;">';
    	ret+='<tr style="text-align:center;">';
    	ret+='<td>取込みボタン<\/td><td>郵便番号<\/td><td>都道府県<\/td><td>市区町村<\/td><td>町域<\/td><\/tr>';
    	for(var i=0;i<zip.ADDRESS_value.length;i++){
    		ret+='<tr><td style="text-align:center;">';
    		ret+='<input type="button" name="" value="利用する" style="color:red" onclick="used('+ i +');return false;">';
    		ret+='<\/td><td>'+zip.result[3]["@attributes"].request_zip_num+'<\/td><td>'+zip.ADDRESS_value[i].value[4]["@attributes"].state+'<\/td><td>'+zip.ADDRESS_value[i].value[5]["@attributes"].city+'<br><font size=1>'+zip.ADDRESS_value[i].value[1]["@attributes"].city_kana+'<\/font><\/td><td>'+zip.ADDRESS_value[i].value[6]["@attributes"].address+'<br><font size=1>'+zip.ADDRESS_value[i].value[2]["@attributes"].address_kana+'<\/font><\/td><\/tr>';
    	}
    	ret+='<\/tbody><\/table>';
    	win.document.writeln("<title>郵便番号「"+zip.result[3]["@attributes"].request_zip_num+"」の同一地域</title>");
    	win.document.writeln(ret);
    	win.document.writeln('<style type="text/css">table.zipcode td{padding:0px 3px;border:1px #897858 solid;}<\/style>');
    	win.document.writeln('<SCRIPT LANGUAGE="JavaScript">function used(i){window.opener.SetZipData(i);window.close();}<\/SCRIPT>');
    	win.document.close();
    }
    function SetZipData(i){
    	ViewForm(true);
    	document.getElementById("zip").value=g_zip.result[3]["@attributes"].request_zip_num;
    	SetZipDataSub(g_zip.ADDRESS_value[i]);
    }
    function SetZipDataSub(zip){
    	document.getElementById("pref").value=zip.value[4]["@attributes"].state;
    	document.getElementById("city").value=zip.value[5]["@attributes"].city;
    	document.getElementById("town").value=zip.value[6]["@attributes"].address;
    	document.getElementById("pref_kana").value=zip.value[0]["@attributes"].state_kana;
    	document.getElementById("city_kana").value=zip.value[1]["@attributes"].city_kana;
    	document.getElementById("town_kana").value=zip.value[2]["@attributes"].address_kana;
    }
    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);
    		}
    	}
    }
    function ViewForm(flag){	//form 表示する(IEでは動的にtableの行を追加できなかったので、このようにした)
    	var ret='<table>';
    	ret+='<tr><th>郵便番号:<\/th><td><input type="text" id="zip" size="9" maxlength="8"><input type="button" style="background-color:#00ddff;" onclick="SearchAddress();return false;" value="住所検索"> ※ハイフォンなしで入力してください。<\/td><\/tr>';
    	ret+='<tr><th>都道府県:<\/th><td><input type="text" id="pref" size="8"><input type="text" id="pref_kana" size="15"><\/td><\/tr>';
    	ret+='<tr><th>市区町村:<\/th><td><input type="text" id="city" size="30"><input type="text" id="city_kana" size="40"><\/td><\/tr>';
    	ret+='<tr><th>町域:<\/th><td><input type="text" id="town" size="30"><input type="text" id="town_kana" size="40"><\/td><\/tr>';
    	if(!flag)	ret+='<tr><th>企業名:<\/th><td><input type="text" id="office" size="30"><input type="text" id="office_kana" size="40"><\/td><\/tr>';	//動的に追加・削除される部分です
    	ret+='<\/table>';
    	document.getElementById("form1").innerHTML=ret;
    }
  5. Html部
  6. <div style="text-align:left;padding-left:10px;">
    	<form id="form1">
    		<table>
    			<tr><th>郵便番号:</th><td><input type="text" id="zip" size="9" maxlength="8"><input type="button" style="background-color:#00ddff;" onclick="SearchAddress();return false;" value="住所検索"> ※ハイフォンなしで入力してください。</td></tr>
    			<tr><th>都道府県:</th><td><input type="text" id="pref" size="8"><input type="text" id="pref_kana" size="15"></td></tr>
    			<tr><th>市区町村:</th><td><input type="text" id="city" size="30"><input type="text" id="city_kana" size="40"></td></tr>
    			<tr><th>町域:</th><td><input type="text" id="town" size="30"><input type="text" id="town_kana" size="40"></td></tr>
    		</table>
    	</form>
    </div>