サンプルのソースコード ———————————————————————-
サンプルのソースコードは次のような感じです。
<html><head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>[ Google Maps ] マーカーをドラッグして座標を取得するサンプル。住所から検索もできます!</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var myLatlng = new google.maps.LatLng(35.6894875,139.6917064); // 座標の初期値
var marker;
// 初期化処理
function initialize() {
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// 地図を生成する
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// マーカーを追加
marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true // ドラッグ可能にする
});
// ドラッグが終了した時の処理
google.maps.event.addListener(marker, "dragend", function() {
setLatLng(marker);
map.setCenter(marker.getPosition());
});
setLatLng(marker); // 座標書き出し
}
// 住所から検索
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
setLatLng(marker); // 座標書き出し
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
// マーカーの位置をテキストフィールドに書きだす。
function setLatLng(marker) {
var p = marker.getPosition();
document.getElementById('latitude').value = p.lat();
document.getElementById('longitude').value = p.lng();
}
</script>
</head>
<body onload="initialize()">
<input id="address" type="textbox" value="Osaka"> <input type="button" value="住所から検索" onclick="codeAddress()">
<div id="map_canvas" style="width:640px; height:480px;"></div>
現在の座標 : <input type="text" id="latitude" name="latitude" size="22"> <input type="text" id="longitude" name="longitude" size="22">
</body>
以上です〜。