やりたいこと
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は非同期です