カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

座標から住所を取得 GoogleMapAPI Geocoder

この記事は最終更新日から1年以上経過しています。

GoogleMap APIを利用して、座標から住所を取得します。

まず、座標オブジェクトを作成します。

location = new google.maps.LatLng([latitude], [longitude]);

ジオコーダーオブジェクトのインスタンスを生成

geocoder = new google.maps.Geocoder();

google.maps.Geocoderクラスのgeocodeメソッドでリクエストを送信し、返ってきたレスポンスを処理するコールバック関数を指定します。
複数の答えが返ってくる場合があるので、結果は配列になっています。

返ってきた結果のフォーマット済の文字列を取得する例

if(geocoder)
{
    geocoder.geocode(
        {location: location},
        function(geo_result, geo_response)
        {
            if(geo_response == "OK") {

                var tmpadd = "";
                tmpadd = geo_result[0].formatted_address;

                alert("住所:" + tmpadd);

            } else {

                alert(geo_response + "\n\n変換できませんでした。");

            }
        }
    );
}


座標は、google.maps.GeocoderRequestオブジェクトを作成し、渡すことも可能です。

request = {
    location: new google.maps.LatLng([latitude], [longitude])
};

住所をバラバラに取り出す
google.maps.GeocoderResult.address_componentsは個別の住所コンポーネントが格納された配列です。
日本の場合、住所が反対から返ってきますので逆順に取り出します。

if(geocoder)
{
    geocoder.geocode(
        request,
        function(geo_result, geo_response)
        {
            if(geo_response == google.maps.GeocoderStatus.OK) {

                var tmpadd = "";

                // 国名はスキップ
                for(i = (geo_result[0].address_components.length - 2); i >= 0; i--) {
                    tmpadd += geo_result[0].address_components[i].long_name;
                }

                alert("住所:" + tmpadd);

            } else {

                alert(geo_response + "\n\n変換できませんでした。");

            }
        }
    );
}

参考URL:
https://developers.google.com/maps/documentation/javascript/geocoding?hl=ja
https://developers.google.com/maps/documentation/javascript/3.exp/reference?hl=ja#Geocoder

この記事がお役に立ちましたらシェアお願いします
7,524 views

コメントは受け付けていません。