小金井にあるWEB制作会社の備忘録

MEMORANDUM

Google Maps API の「Geocoding」を使用して、フォームに入力された住所から緯度・経度を取得する

管理画面等を使用して店舗を追加していく際に、一つづつ確認しながら地図を埋め込むことも可能ですが、入力した住所から動的に地図を生成する方法を実装していた際のコードをメモ。

Geocodingを使用した緯度経度の取得方法

実装する前にAPIキーを取得する

googlemapの「geocoding」機能を使用するためにはAPIキーを取得する必要があります。
google APIキーは「Google Cloud Platform」よりプロジェクトを作成して取得、更にAPIライブラリの中から「Geocoding API」を有効化。
他サイトで利用できないよう認証情報ページで使用サイトと使用APIを制限します。

ヘッドにAPIキーを記載する

取得したAPIキーを、対象ページのヘッド内に下記を記載。

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

ジオコーディングを実装する

HTML

<form id="addressForm">
<table>
<tr>
<th>住所</th>
<td>
<input type="text" name="address" id="address" value="" onblur="initialize(this)">
<input type="hidden" name="latitude" id="latitude" value="">
<input type="hidden" name="longitude" id="longitude" value="">
</td>
</tr>
</table>
<button type="submit" name="submit">送信</button>
</form>

javascript

function initialize(obj){
	var geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(-34.397, 150.644);
	var address = document.getElementById('address').value;
	geocoder.geocode({'address': address},function(results,status){
		if (status == 'OK') {
			var latlng = results[0].geometry.location;
			document.addressForm.latitude.value = latlng.lat();
			document.addressForm.longitude.value = latlng.lng();
		}else{
			alert('Geocode was not successful for the following reason: ' + status);
		}
	});
}

後は用途に応じてフォームから取得した値をPHP等を使用してデータベースに保存します。

同一カテゴリーの記事