メニュー
E-Mail

ASP.Netのお勉強
VB.Netのお勉強
Excel マクロ・VBAのお勉強
PHPのお勉強
Webデザインのお勉強
Javaのお勉強
総合サイトCocoaLiz
ネイルサロン検索
エステサロン検索
アロマサロン検索
アイビューティーサロン検索
|
住所から緯度経度を取得
入力された住所、もしくは地名から経度緯度を取得し、
地図に表示します。
要点だけ説明すると、、
○ 緯度経度を取得
google.maps.Geocoderを生成し
geocodeメソッドに住所を渡します。
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(res, state) {
//取得に成功
if (state == google.maps.GeocoderStatus.OK) {
//取得に失敗
} else {
}
}
|
○ 地図に結果を表示
無事に結果を取得できたら、地図に結果を表示します。
マーカを作成し、情報窓に取得した結果(住所、緯度経度)を表示します。
※複数の結果が返ってきます。
サンプルでは、ひとまず一番最初の結果だけを表示します。
//取得に成功
if (state == google.maps.GeocoderStatus.OK) {
//入力さらた住所を中心にマップを表示
map.setCenter(res[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: res[0].geometry.location
});
//情報窓に住所と緯度経度を表示
var htmlstr = res[0].address_components[0].long_name;
htmlstr += "<br>";
htmlstr += res[0].geometry.location;
var infowindow = new google.maps.InfoWindow({
content: htmlstr
});
infowindow.open(map,marker);
}
|
○ 作ったサンプルサイトは、こちらです。
○コードは、下記。
<html lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Google Map API V3</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(35.681382, 139.766084);
var options = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), options);
}
function getLatlng() {
//入力された住所
var address = document.getElementById("address").value;
//緯度、経度を取得
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(res, state) {
//取得に成功した場合
if (state == google.maps.GeocoderStatus.OK) {
//入力さらた住所を中心にマップを表示
map.setCenter(res[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: res[0].geometry.location
});
//情報窓に住所と緯度経度を表示
var htmlstr = res[0].address_components[0].long_name;
htmlstr += "<br>";
htmlstr += res[0].geometry.location;
var infowindow = new google.maps.InfoWindow({
content: htmlstr
});
infowindow.open(map,marker);
//失敗したらアラート
} else {
alert("失敗しました、、、" + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div>
住所、もしくは地名を入力してください。<br>
<input id="address" type="textbox" style="width:200px" value="新宿">
<input type="button" value="検索" onclick="getLatlng()">
</div>
<div id="map" style="width: 600px; height: 400px;"></div>
</body>
</html>
|
|
|