LoginSignup
1
2

More than 5 years have passed since last update.

Google Maps API Geocoding Service で緯度経度を取得しその場所を表示する

Last updated at Posted at 2018-06-28

やりたいこと

Geocoding Serviceを使って画面から入力された場所へ移動したい

コード

sample.html
<div>
    <label><input type="text" id="addressText"></label>
    <button id="search">検索</button>
<div>

こんなの↑があったとして表示したい場所を入力し検索ボタンを押下するとします(適当)。

gmapsample.js
$(document).on('click', '#search', function () {
    const place = $('#addressText').val();
    getLatLng(place);
});

function getLatLng(place) {
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        address: place
    }, function(results, status) {
        //成功
        if (status == google.maps.GeocoderStatus.OK) {
            //同じズーム値のまま
//          map.panTo(results[0].geometry.location);
//          map.setCenter(results[0].geometry.location);
            //表示領域を調整
            map.fitBounds(results[0].geometry.viewport);
        //失敗
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

画面から入力された値をGeocoderに渡して結果を取得し移動するという流れです。
画面からの入力は「東京」とか「ダイバーシティ」とかどこかの住所とかを想定しています。
移動の箇所ですが、今のズーム値のまま表示したい場合はmap.panTo(results[0].geometry.location);map.setCenter(results[0].geometry.location);とするといけます。
また、表示領域を調整していい感じに表示したい場合はmap.fitBounds(results[0].geometry.viewport);とするといけます。

ちなみに、Geocoding Serviceは非同期です:zap:

参考:Geocoding Service

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2