はじめに
Google Maps JavaScript APIを利用して、緯度経度の数値から住所を検索する方法を紹介します。
キーを取得する
Google Maps JavaScript APIを利用するにはキーを取得する必要があります。
キーを取得する
下記のページの「キーの取得」ボタンを押して「Create a new project」を選択します。
ポップアップが表示されたらプロジェクト名を入力して「NEXT」をクリックして暫く待つとAPIキーが表示されます。
https://developers.google.com/maps/documentation/javascript/?hl=ja
コード
位置情報から住所を取得するには逆ジオコーディングを利用します。
以下は東京駅の緯度経度情報から住所を取得するコードです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | (function(){ varrequestAjax=function(endpoint,callback){ varxhr=newXMLHttpRequest(); xhr.onreadystatechange=function(){ if(this.readyState==4&&this.status==200){ callback(this.response); } }; xhr.responseType='json'; xhr.open('GET',endpoint,true); xhr.send(); }; // 東京駅の緯度経度 varlatitude='35.6811673'; varlongitude='139.7648629'; varapiKey='your-key'; varrequestURL='https://maps.googleapis.com/maps/api/geocode/json?language=ja&sensor=false'; requestURL+='&latlng='+latitude+','+longitude; requestURL+='&key='+apiKey; requestAjax(requestURL,function(response){ if(response.error_message){ console.log(response.error_message); }else{ varformattedAddress=response.results[0]['formatted_address']; // 住所は「日本、〒100-0005 東京都千代田区丸の内一丁目」の形式 vardata=formattedAddress.split(' '); if(data[1]){ // id=addressに住所を設定する document.getElementById('address').innerHTML=data[1]; } } }); })(); |
参考
https://developers.google.com/maps/documentation/geocoding/intro?hl=ja#ReverseGeocoding
https://qiita.com/ikuwow/items/ed5f3c9ee0bd6147b7f3
さいごに
緯度経度情報から住所を検索する方法を紹介しました。