Google Maps API V3
(ページの作成:「== 概要 == Google Maps API V3を使ってみる。 ==地図の表示== まずはここから。 <pre> <!DOCTYPE html> <html> <head> <meta http-equiv="content-t...」) |
2013年4月14日 (日) 08:45時点における版
目次 |
概要
Google Maps API V3を使ってみる。
地図の表示
まずはここから。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<title>Google Maps API サンプル</title>
</head>
<body>
<p>Google Maps APIを使ったサンプルです。</p>
</body>
</html>
Google Maps APIの取得
- GoogleのサイトからAPIをインクルードする。
- センサーの指定sensor=XXXXは必須
- trueの場合、端末のGPSなどから現在位置情報を使用する。
- flaseの場合、現在位置情報は使用しない。
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
必要に応じて、言語の指定などを指定する場合は、以下の通り。(しなくてもよい)
- デフォルトでは、ブラウザの言語設定になる。
- 以下は、明示的に言語を日本語に設定している
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=ja"></script>
英語設定の場合は以下の通り
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
地図表示エリアの記述
body内にdivで地図を表示する領域を指定する。
- idでdiv要素に名前をつける。この例は、map_canvas
- widthとheightで領域のピクセルを指定
<div id="map_canvas" style="width:500px; height:300px"></div>
CSSを記述する。
- ブラウザによっては、サイズが指定されていないと、0 x 0 ピクセルと見なされて地図が表示されないことがある。
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
地図表示のJavaScript
head内に地図を定義するJavaScriptを<script>タグで囲って記述する。
- google.maps.LatLngで緯度・経度クラスオブジェクトを作る
- 地図表示に使う情報をoptionとして指定
- 必須のoptionは、zoom,center,mapTypeId
- 他のoptionは、https://developers.google.com/maps/documentation/javascript/reference?hl=ja#MapOptions
- google.maps.Mapで地図クラスオブジェクトを作る
- 地図をbody内に表示するdiv領域map_canvasを指定する。
<script type="text/javascript">
//<![CDATA[
function initialize() {
var latlng = new google.maps.LatLng(35.463536,139.32945);
var opts = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), opts);
}
//]]>
</script>
地図表示スクリプトの呼び出し関数
bodyタグにonloadオプションで表示と同時に呼び出される関数initialize()を指定する。
<body onload="initialize()">
完成版
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<title>Google Maps API サンプル</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
function initialize() {
var latlng = new google.maps.LatLng(35.463536,139.32945);
var opts = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), opts);
}
//]]>
</script>
</head>
<body onload="initialize()">
<p>Google Maps APIを使ったサンプルです。</p>
<div id="map_canvas" style="width:500px; height:300px"></div>
</body>
</html>
- 緯度経度、ズームの値の取得は、地図上で右クリック
- 表示場所、ズーム、マップタイプを変えてみる
- HYBRID This map type displays a transparent layer of major streets on satellite images.
- ROADMAP This map type displays a normal street map.
- SATELLITE This map type displays satellite images.
- TERRAIN This map type displays maps with physical features such as terrain and vegetation.
- MapTypeIdについては、以下を参照
ボタンで地図の変更
地図の種類の変更
mapオブジェクトをグローバルに変更
var map;
衛星地図に変更する関数を書く。
// 衛星地図に変更する
function changeMapType() {
map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
}
上記関数を呼び出すボタンを作る。
<input type="button" value="衛星地図に変更" onClick="changeMapType()" />
位置の移動
中心位置を変更
var osaka = new google.maps.LatLng(34.694203,135.502625);
// 中心位置を変更する
function changeCenter() {
map.setCenter(osaka);
}
滑らかに移動
var senzu = new google.maps.LatLng(35.46628,139.337497);
//滑らかに移動
function changeCenterSenzu() {
map.panTo(senzu);
}
指定したピクセルだけ移動
- 地図の座標系
- 西から東(x 値の場合)に増える
- 北から南(y 値の場合)に増える
//指定したピクセルだけ移動
function gotoNorthEast() {
map.panBy(100,-50);
}
地図の座標の取得
var latlng = map.getCenter(); var lat = latlng.lat(); var lng = latlng.lng();
イベントリスナー
地図上をクリックすると、緯度・経度がアラートウィンドウに表示される。
// clickイベントを取得するListenerを追加
google.maps.event.addListener(map, 'click', clickEventFunc);
function clickEventFunc(event) {
alert(event.latLng.toString());
}
Mapクラスにおける「click」イベント発生時に呼び出されるfunctionの引数は、MouseEvent。
- https://sites.google.com/site/gmapsapi3/Home/v3_reference
- https://developers.google.com/maps/documentation/javascript/events?hl=ja
地図上をクリックすると、緯度・経度がtable内に表示される。
google.maps.event.addListener(map, 'click', clickEventFunc2);
function clickEventFunc2(event) {
document.getElementById("show_lat").innerHTML = event.latLng.lat();
document.getElementById("show_lng").innerHTML = event.latLng.lng();
}
<table border="1"> <tr><th>LAT</th><td id="show_lat"></td></tr> <tr><th>LNG</th><td id="show_lng"></td></tr> </table>
オーバーレイ
オーバーレイは緯度/経度座標に固定された地図上のオブジェクト。 たとえば、マーカー、情報ウィンドウ、ポリライン、ポリゴン・・・
マーカー
Markerの設定
var mkopts = {
position: latlng,
map: map,
title: "Tokyo Koogei"
};
var marker = new google.maps.Marker(mkopts);
マーカーをボタンで表示・非表示
function markerOn() {
marker.setVisible(true);
}
function markerOff() {
marker.setVisible(false);
}
マーカー<br> <input type="button" value="出す" onclick="markerOn()" /> <input type="button" value="消す" onclick="markerOff()" />
マーカーをドラッグ可能にする/ マーカーをアニメーション表示する
var mkopts = {
position: latlng_koogei,
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
//animation: google.maps.Animation.BOUNCE,
title: "Tokyo Koogei大学"
};
マーカー移動に関する他のオプションも試してみる。
dragCrossMove bouncy autoPan
マーカーアニメーション表示のトグル関数
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
マーカーとして独自のアイコンを設定
var image = "./img/icon.png";
var mkopts01 = {
position: senzu,
map: map,
title: "千頭橋",
icon: image
};
var marker1 = new google.maps.Marker(mkopts01);
より複雑な独自マーカーを配列で指定
var places = [
['小鮎幼稚園', 35.46266214773244, 139.32520138092036, 4],
['小鮎中', 35.46203296822141, 139.32327019042964, 5],
['島津製作所', 35.46112414468374, 139.326574671936, 3],
['小鮎郵便局', 35.46378067693368, 139.3217681533813, 2],
['本禅時', 35.45944628963795, 139.3226693756103, 1]
];
function setMarkersOn(map, locations) {
var image = new google.maps.MarkerImage('img/flag.png',
new google.maps.Size(20, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shadow = new google.maps.MarkerImage('img/flag_shadow.png',
new google.maps.Size(37, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var places = locations[i];
var myLatLng = new google.maps.LatLng(places[1], places[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,
title: places[0],
zIndex: places[3]
});
}
}
情報ウィンドウ(ふきだし)
情報ウィンドウの表示
var latlng = new google.maps.LatLng(35.463536,139.32945);
var iwopts = {
content: 'こうげい',
position: latlng
};
var infowindow = new google.maps.InfoWindow(iwopts);
infowindow.open(map);
情報ウィンドウを閉じる
infowindow.close();
ポリライン、ポリゴン
- https://developers.google.com/maps/documentation/javascript/overlays?hl=ja#Polylines
- https://developers.google.com/maps/documentation/javascript/overlays?hl=ja#Polygons
円、矩形(四角形)
//Circle生成
var cityCircle;
function setCircle() {
var circleOpts = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
center: senzu,
radius: 200
};
cityCircle = new google.maps.Circle(circleOpts);
}
function circleOn() {
cityCircle.setMap(map);
}
function circleOff() {
cityCircle.setMap(null);
}
//Rectangle生成
var cityRectangle;
function setRectangle() {
var cityBounds = new google.maps.LatLngBounds(honzen,senzu);
var rectangleOpts = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
bounds: cityBounds
};
cityRectangle = new google.maps.Rectangle(rectangleOpts);
}
function rectangleOn() {
cityRectangle.setMap(map);
}
function rectangleOff() {
cityRectangle.setMap(null);
}
表示・非表示ボタン
円
<input type="button" value="描画" onClick="circleOn()" />
<input type="button" value="消す" onClick="circleOff()" />
矩形
<input type="button" value="描画" onClick="rectangleOn()" />
<input type="button" value="消す" onClick="rectangleOff()" />
ジオコーディング
- https://developers.google.com/maps/documentation/geocoding/index?hl=ja
- Google Maps JavaScript API V3 サービス
住所から緯度経度情報を取得
住所や場所を入力して、地図にマーカーを表示する。
var map;
var geocoder;
function initialize() {
//ジオコーダの設定
geocoder = new google.maps.Geocoder();
//地図の設定
var opts = {
zoom: 15,
center: latlng_koogei,
mapTypeId: google.maps.MapTypeId.ROADMAP
//mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map_canvas"), opts);
}
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);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
検索結果は、resultオブジェクトに入っており、 result[0]が第1候補、result[1]が第2候補、result[2]が第3候補というように、候補順に結果が配列に収められている。
住所入力テキストボックスと検索ボタン
<div> 場所を入力: <input id="address" type="textbox" value=""> <input type="button" value="Encode" onclick="codeAddress()"> </div>
緯度経度情報から住所を取得(リバースジオコーディング)
イベントリスナーを利用して、クリックした位置の緯度経度情報から、住所を取得してテーブルに表示する。
google.maps.event.addListener(map, 'click', clickGetLatlng);
function clickGetLatlng(event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
marker = new google.maps.Marker({
position: latlng,
map: map
});
document.getElementById("show_address").innerHTML = results[0].formatted_address;
}
} else {
alert("Geocoder エラー: " + status);
}
});
}
緯度、経度、住所を表示するテーブル
<table border="1"> <tr><th>緯度</th><td id="show_lat">ido</td></tr> <tr><th>経度</th><td id="show_lng">keido</td></tr> <tr><th>住所</th><td id="show_address">address</td></tr> </table>
緯度経度情報から住所を取得して、テーブル内に記述する関数
function codeLatLng(lat,lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
document.getElementById("show_address").innerHTML = results[0].formatted_address;
}
} else {
alert("Geocoder エラー: " + status);
}
});
}
GPSによる現在位置の取得GeoLocation
sensorをtrueにする。
<script src="http://maps.google.com/maps/api/js?v=3&sensor=true" type="text/javascript" charset="UTF-8"></script>
navigator.geolocation.getCurrentPositionで現在位置の緯度経度情報をGPSから取得する。
var map;
function initialize() {
// Google Mapで利用する初期設定用の変数
var latlng = new google.maps.LatLng(0, 0);
var opts = {
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng
};
map = new google.maps.Map(document.getElementById("map_camvas"), opts);
// W3C Geolocationを使う
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(handleGeolocation,handleNoGeolocation);
} else {
alert("W3C Geolocationがありません");
}
}
function handleGeolocation(position) {
// 位置情報を取得
var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(latlng);
}
// エラーの内容を表示
function handleNoGeolocation(err) {
var errCodeStr;
// エラー内容を示す文字列を用意。
if (err.code == 0) {
errCodeStr = "UNKNOWN_ERROR";
} else if (err.code == 1) {
errCodeStr = "PERMISSION_DENIED";
} else if (err.code == 2) {
errCodeStr = "POSITION_UNAVAILABLE";
} else if (err.code == 3) {
errCodeStr = "TIMEOUT";
} else {
errCodeStr = "想定外";
}
var errStr = "失敗 [" + err.code + "] " + errCodeStr;
// 失敗内容をふきだしで表示。位置はいい加減。
alert(errStr);
}
サイドバーとの連動
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&v=3"></script>
<script type="text/javascript">
//<![CDATA[
var restaurantList = [
{"latlng":[35.454839,139.34432],name:"○屋製麺店",comment:"味玉塩ラーメンがおすすめ"},
{"latlng":[35.443127,139.299007],name:"セルバジーナ",comment:"自家製地ビールのイタリアン"},
{"latlng":[35.44503,139.312407],name:"アマンダンヒルズ",comment:"身近なフレンチレストラン"},
{"latlng":[35.436093,139.314078],name:"HAPPY cafe 食堂",comment:"カレーとドリアがおいしい"},
{"latlng":[35.490311,139.364496],name:"My Lan 美蘭",comment:"ベトナム料理がおいしい"},
{"latlng":[35.464021,139.331918],name:"工芸大学食MESA",comment:"カフェテリア形式レストラン"}
];
var map;
var infowindow;
var geocoder;
function initialize() {
//地図の生成
var opts = {
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), opts);
//地図上にマーカーを配置していく
var bounds = new google.maps.LatLngBounds();
var restaurant, i, latlng;
for (i in restaurantList) {
//マーカーを作成
restaurant = restaurantList[i];
latlng = new google.maps.LatLng(restaurant.latlng[0], restaurant.latlng[1]);
bounds.extend(latlng);
var marker = createMarker(latlng, restaurant.name, restaurant.comment);
//サイドバーのボタンを作成
createMarkerButton(marker);
}
//マーカーが全て収まるように地図の中心とズームを調整して地図表示
map.fitBounds(bounds);
}
function createMarker(latlng, name, comment) {
//マーカーを作成
var marker = new google.maps.Marker({
position : latlng,
map : map,
title : name
});
//マーカーがクリックされたら、情報ウィンドウを表示
google.maps.event.addListener(marker, "click", function(){
if(infowindow) infowindow.close();
var iwopts = {
content: "<b>" + name + "</b><br>" + comment
};
infowindow = new google.maps.InfoWindow(iwopts);
infowindow.open(map, marker);
});
return marker;
}
function createMarkerButton(marker) {
//サイドバーにマーカ一覧を作る
var ul = document.getElementById("marker_list");
var li = document.createElement("li");
var title = marker.getTitle();
li.innerHTML = title;
ul.appendChild(li);
//サイドバーがクリックされたら、マーカーを擬似クリック
google.maps.event.addDomListener(li, "click", function(){
google.maps.event.trigger(marker, "click");
});
}
window.onload = initialize;
//]]>
</script>
</head>
<body>
<h1>厚木のグルメマップ</h1>
<div id="map_canvas"></div>
<div id="side_bar">
<ul id="marker_list"></ul>
</div>
</body>
</html>
html, body {
width : 100%;
height : 100%;
margin : 0;
}
#map_canvas {
width:100%;
height:100%;
}
body #side_bar {
width:20%;
height:100%;
float:right;
overflow-y: scroll;
}
body #map_canvas {
width:80%;
height:80%;
float:left;
}
body ul#marker_list {
list-style-type: none;
padding:0;
}
body ul#marker_list li {
cursor: pointer;
margin: 5px;
border: 1px solid #888;
padding: 5px;
font-size: 75%;
}