Google Maps APIで住所を緯度と経度に変換してみます。
サンプルコード
指定した住所を緯度と経度に変換して、その位置にマーカーを立ててみます。
HTML
<div id="map"></div>
JavaScript
var map;
var geocoder;
var marker;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 35.712074, lng: 139.79843},
zoom: 16
});
geocoder = new google.maps.Geocoder(); // ジオコードの準備
geocoder.geocode({ // ジオコードのリクエスト
'address': '雷門二丁目' // 調べる住所
}, function(results, status) { // ジオコードのリクエスト結果
if (status === google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
} else {
alert('Error: ' + status);
}
});
}
| new google.maps.Geocoder(); | ジオコード(住所変換)のリクエストをGoogleサーバへ送信する準備。 |
|---|---|
| geocode(request:GeocoderRequest, callback:function(Array<GeocoderResult>, GeocoderStatus)) | ジオコードのリクエスト。 GeocoderRequestの内容でリクエストを送信して、リクエスト結果とステータスをGeocoderResultとGeocoderStatusに返す。 リクエストはaddress 、location、placeIdのいずれかを必須で指定する。 |
ジオコードをリクエストした結果(GeocoderResult)は以下のような形で返ってきます。
リクエスト結果
results[]: {
types[]: string,
formatted_address: string,
address_components[]: {
short_name: string,
long_name: string,
postcode_localities[]: string,
types[]: string
},
partial_match: boolean,
place_id: string,
postcode_localities[]: string,
geometry: {
location: LatLng,
location_type: GeocoderLocationType
viewport: LatLngBounds,
bounds: LatLngBounds
}
}
緯度・経度から住所を調べる
上記とは逆に、緯度・経度から住所を調べてみます。
JavaScript
var map;
var geocoder;
var marker;
var latlng = {lat: 35.7147651, lng: 139.7966553}; // 調べる緯度と経度
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 35.712074, lng: 139.79843},
zoom: 16
});
infowindow = new google.maps.InfoWindow;
geocoder = new google.maps.Geocoder(); // ジオコードの準備
geocoder.geocode({ // ジオコードのリクエスト
'location': latlng // 調べる緯度と経度
}, function(results, status) { // ジオコードのリクエスト結果
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Error: ' + status);
}
});
}
緯度・経度から住所を調べるデモページ
今回はresults[1].formatted_addressで住所を取得して、infowindowで表示しています。
resultsは複数返ってくることがほとんどで、今回の場合はそれぞれ以下のように格納されています。
results[0].formatted_address // 日本, 〒111-0032 東京都台東区浅草2丁目3−1 results[1].formatted_address // 日本, 〒111-0032 東京都台東区浅草2丁目3 results[2].formatted_address // 日本, 〒111-0032 東京都台東区浅草2丁目 results[3].formatted_address // 日本, 〒111-0032 東京都台東区浅草 results[4].formatted_address // 日本, 東京都台東区 results[5].formatted_address // 日本 東京 results[6].formatted_address // 日本
この他にもPlace IDから住所を調べる方法などありますが、あまり使う場面がなさそうな気がするので今回は割愛します。
各オプションについてはGeocoderRequestのオプションやGeocoderResultのオプション、GeocoderStatusのオプションなどでご確認ください。
【参考サイト】
- Geocoding Service | Google Maps JavaScript API | Google Developers
- Google Maps JavaScript API V3 Reference | Google Maps JavaScript API | Google Developers
コメントが承認されるまで時間がかかります。