「Google Maps JavaScript API v3」の基本的な使い方について紹介します。マップの設置、マーカー表示、吹き出し表示、ポリライン表示など確認していきます。
Googleマップを設置
HTML/CSS
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow,noarchive" />
<title>Smple|Google Maps</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/base.js"></script>
<style>
#map_canvas {
width: 100%;
height: 500px;
}
#zoomopts {
margin-top: 10px;
}
#centeropts{
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Smple|Google Maps</h1>
<div id="map_canvas"></div>
<div id="zoomopts">
<input type="button" id="method11" value="zoomを5に変更"/>
<input type="button" id="method12" value="zoomを10に変更"/>
<input type="button" id="method13" value="zoomを13に変更"/>
<input type="button" id="method14" value="zoomを15に変更"/>
<input type="button" id="method15" value="zoomを17に変更"/>
</div>
<div id="centeropts">
<input type="button" id="method21" value="centerを東京駅に変更"/>
<input type="button" id="method22" value="centerを新宿駅に変更"/>
<input type="button" id="method23" value="centerを品川駅に変更"/>
</div>
</body>
</html>
■9行目
Google Maps APIを使用するためのjavascriptを読み込んでいます。「sensor」パラメータでユーザー位置情報の使用するか指定します。sensorパラメータの指定は以前は、必須でしたが現在は必要ないようです。
なお、https上で地図を表示するには、Google Maps APIの読み込み先もhttpsにします。
■28行目
GoogleMapを設置するためのエリアを記述しています。
JavaScript
$(function () {
var latlng = new google.maps.LatLng(35.681382, 139.76608399999998);
var opts = {
zoom: 15,
center: latlng,
overviewMapControl: true,
overviewMapControlOptions: {opened: 1},
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), opts);
$("#method11").click(function () {
map.setZoom(5);
});
$("#method12").click(function () {
map.setZoom(10);
});
$("#method13").click(function () {
map.setZoom(13);
});
$("#method14").click(function () {
map.setZoom(15);
});
$("#method15").click(function () {
map.setZoom(17);
});
$("#method21").click(function () {
// 東京
var latlng = new google.maps.LatLng(35.681382, 139.76608399999998);
map.setCenter(latlng);
});
$("#method22").click(function () {
// 新宿
var latlng = new google.maps.LatLng(35.690921, 139.70025799999996);
map.setCenter(latlng);
});
$("#method23").click(function () {
// 品川
var latlng = new google.maps.LatLng(35.630152, 139.74044000000003);
map.setCenter(latlng);
});
});
■2行目
地図上で位置座標を指定する際に、LatLngクラスで値のオブジェクトを利用します。
■3行目~10行目
地図のオプションを設定しています。
オプション | 概要 |
---|---|
zoom | 地図の拡大率 |
center | 中心座標 |
overviewMapControl | trueを指定すると、地図を俯瞰するウィンドウが表示される。 |
overviewMapControlOptions | {opened:1}と指定するとoverviewMapControlをデフォルトで開いた状態とする。 |
scaleControl | trueを指定すると、距離の目安を確認するスケールが表示される。 |
mapTypeId | HYBRID:航空写真とロードマップ。 ROADMAP:ロードマップ。 SATELLITE:航空写真。 TERRAIN:地形的な特徴を反映。 |
■11行目
Mapオブジェクトを生成して地図を表示させています。引数として「地図を表示させる場所(要素)」と「オプション」を渡します。
■14行目
setZoomメソッドで拡大率を変更しています。
■33行目
setCenterメソッドで中心座標を変更しています。
マーカー表示(Marker)
HTML/CSS
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow,noarchive" />
<title>Smple|Google Maps</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/marker.js"></script>
<style>
#map_canvas {
width: 100%;
height: 500px;
}
#markeropts {
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Smple|Google Maps</h1>
<div id="map_canvas"></div>
<div id="markeropts">
<input type="button" id="method11" value="マーカーオプションを変更"/>
</div>
</body>
</html>
JavaScript
$(function () {
var markers = [];
var latlng = new google.maps.LatLng(35.681382, 139.76608399999998); // 東京駅
var latlng2 = new google.maps.LatLng(35.675069, 139.763328); // 有楽町駅
var opts = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), opts);
var markerOption1 = {
position: latlng,
map: map,
animation: google.maps.Animation.DROP
};
var markerOption2 = {
position: latlng2,
map: map,
animation: google.maps.Animation.BOUNCE
};
markers[0] = new google.maps.Marker(markerOption1);
markers[1] = new google.maps.Marker(markerOption2);
google.maps.event.addListener(markers[0], "click", function () {
alert("東京駅です。");
});
google.maps.event.addListener(markers[1], "click", function () {
alert("有楽町駅です。");
});
$("#method11").click(function () {
var animation = markers[1].getAnimation();
if (animation === 1) {
markers[1].setAnimation(google.maps.Animation.DROP);
markers[1].setIcon("http://wxxxx/markerimg.png");
} else {
markers[1].setAnimation(google.maps.Animation.BOUNCE);
markers[1].setIcon(null);
}
});
});
■13行目~17行目
1つ目のマーカーのオプションを設定しています。
オプション | 概要 |
---|---|
position | 位置座標 [LatLngクラスで指定] |
map | 設置するMapオブジェクト |
animation | google.maps.Animation.DROP ⇒ 上から落ちてきて配置される。 google.maps.Animation.BOUNCE ⇒ ずっとバウンドし続ける。 |
■23行目
1つ目のマーカーを生成しています。
■26行目
1つ目のマーカーがクリックされた時のイベントを設定しています。
■34行目
2つ目のマーカーに適用されているアニメーションを取得しています。
BOUNCEであれば戻り値として1を取得します。
■36行目
setAnimationメソッドでアニメーションを変更しています。
■37行目
setIconメソッドでアイコン画像を変更しています。
マーカーが多いとき
地図上に表示するマーカーが多いとき、動作が重くなり、マーカーが重なって見づらくなります。そのようなときは、MarkerClustererを利用してマーカーをまとめて表示するなどの対応が必要になってくるかと思います。
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script>
$(function () {
var markers = [];
// マーカの作成
for(i = 0; i < 1000; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat[i], lng[i]),
});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers, {
maxZoom:12,
gridSize:50,
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
});
吹き出し表示(InfoWindow)
HTML/CSS
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow,noarchive" />
<title>Smple|Google Maps</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/infowindow.js"></script>
<style>
#map_canvas {
width: 100%;
height: 500px;
}
#infoopts {
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Smple|Google Maps</h1>
<div id="map_canvas"></div>
<div id="infoopts">
<input type="button" id="method11" value="吹き出しを変更"/>
</div>
</body>
</html>
JavaScript
$(function () {
var markers = [];
var infoWindows = [];
var latlng = new google.maps.LatLng(35.681382, 139.76608399999998); // 東京駅
var latlng2 = new google.maps.LatLng(35.675069, 139.763328); // 有楽町駅
var opts = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), opts);
var markerOption1 = {
position: latlng, //位置座標 [LatLngクラスで指定]
map: map, //設置するMapオブジェクト
};
markers[0] = new google.maps.Marker(markerOption1);
var infoWindowOption1 = {
content: "東京駅"
}
infoWindows[0] = new google.maps.InfoWindow(infoWindowOption1);
infoWindows[0].open(map, markers[0]);
var infoWindowOption2 = {
position: latlng2,
content: "有楽町駅",
};
infoWindows[1] = new google.maps.InfoWindow(infoWindowOption2);
infoWindows[1].open(map);
$("#method11").click(function () {
var content;
var latlng;
content = infoWindows[1].getContent()
if (content === "有楽町駅") {
latlng = new google.maps.LatLng(35.682413, 139.77391899999998); // 日本橋駅
infoWindows[1].setPosition(latlng);
infoWindows[1].setContent("日本橋駅");
} else {
latlng = new google.maps.LatLng(35.675069, 139.763328); // 有楽町駅
infoWindows[1].setPosition(latlng);
infoWindows[1].setContent("有楽町駅");
}
});
});
■20行目~22行目
吹き出しのオプションを設定しています。
オプション | 概要 |
---|---|
content | 表示内容 |
position | 位置座標 [LatLngクラスで指定] |
■23行目
InfoWindowオブジェクトを生成しています。
■24行目
openメソッドで吹き出しを表示させます。引数としてmarkers[0]を指定してるので、markers[0]のマーカー上に吹き出しが表示されます。
■36行目
getContentメソッドで表示内容を取得しています。
■39行目
setPositionメソッドで位置を再設定しています。
■40行目
setContentメソッドで表示内容を再設定しています。
ポリライン表示(Polyline)
HTML/CSS
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow,noarchive" />
<title>Smple|Google Maps</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/pollyline.js"></script>
<style>
#map_canvas {
width: 100%;
height: 500px;
}
#infoopts {
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Smple|Google Maps</h1>
<div id="map_canvas"></div>
<div id="infoopts">
<input type="button" id="method11" value="位置座標取得"/>
</div>
</body>
</html>
JavaScript
$(function () {
var polylines = [];
var latlng = new google.maps.LatLng(35.681382, 139.76608399999998); // 東京駅
var latlng2 = new google.maps.LatLng(35.675069, 139.763328); // 有楽町駅
var opts = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), opts);
var polylineOption = {
path: [latlng, latlng2],
map: map,
editable: true,
strokeColor: "#F00",
};
polylines[0] = new google.maps.Polyline(polylineOption);
$("#method11").click(function () {
var paths = polylines[0].getPath().getArray();
var str = "";
for (var i = 0, l = paths.length; l > i; i++) {
str += paths[i].toString() + "\r\n";
}
alert(str);
});
});
■14行目~19行目
ポリラインのオプションを設定しています。
オプション | 概要 |
---|---|
path | 線を結ぶ位置座標。 |
map | 設置するMapオブジェクト。 |
editable | trueを指定すると、編集可能になる。 |
strokeColor | 線の色。 |
■20行目
Polylineオブジェクトを生成しています。
■24行目
線が通る座標を配列形式で取得しています。
住所を使って表示(Geocoding)
HTML/CSS
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow,noarchive" />
<title>Smple|Google Maps</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/geocoder.js"></script>
<style>
#map_canvas {
width: 100%;
height: 500px;
}
#geocoderopts {
margin-top: 10px;
}
p {
margin: 0px;
}
</style>
</head>
<body>
<h1>Smple|Google Maps</h1>
<div id="map_canvas"></div>
<div id="geocoderopts">
<p>変更する位置情報を入力してください(例:新宿駅、富士山、住所など)</p>
<input type="text" id="address" size="30" />
<input type="button" id="addressbtn" value="位置変更" /><br />
</div>
</body>
</html>
JavaScript
$(function () {
var latlng = new google.maps.LatLng(35.681382, 139.76608399999998); // 東京駅
var opts = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), opts);
$("#addressbtn").click(function () {
var request = {
address: $("#address").val()
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode(request, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
var content = request.address + "<br>" +
"緯度:" + location.lat() + "<br>" +
"経度:" + location.lng()
var infoWindowOption = {
position: location,
content: content
};
var infoWindows = new google.maps.InfoWindow(infoWindowOption);
infoWindows.open(map);
map.panTo(location);
$("#address").val("");
}
});
});
});
■15行目
Geocoderオブジェクトを生成しています。
■16行目~34行目
geocoderメソッドで住所から緯度経度を算出しています。
ルート表示(DirectionsRenderer)
HTML/CSS
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow,noarchive" />
<title>Smple|Google Maps</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/directions.js"></script>
<style>
#map {
width: 100%;
}
#map_canvas {
width: 50%;
height: 500px;
float: left;
}
#map_panel {
width: 50%;
height: 500px;
overflow: scroll;
float: right;
}
</style>
</head>
<body>
<h1>Smple|Google Maps</h1>
<div id="map">
<div id="map_canvas"></div>
<div id="map_panel"></div>
</div>
<div id="distance">
</body>
</html>
JavaScript
$(function () {
var latlng = new google.maps.LatLng(35.681382, 139.76608399999998); // 東京駅
var opts = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), opts);
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById("map_panel"));
var wayPoints = [
{location: "日本橋駅"},
{location: "茅場町駅"}
];
var request = {
origin: "東京駅",
destination: "有楽町駅",
travelMode: google.maps.DirectionsTravelMode.WALKING,
waypoints: wayPoints
};
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
var distance = getDistance(result.routes[0].legs);
$("#distance").text("合計距離:" + distance + "km");
}
});
function getDistance(legs) {
var journey = 0;
for (var i in legs) {
journey += legs[i].distance.value;
}
return journey / 1000;
}
});
■10行目~33行目
DirectionsRendererクラスとDirectionsServiceクラスを利用してルート表示します。
■19行目~24行目
DirectionsServiceオブジェクトのrouteメソッドの引数として渡すオプションを設定してます。
オプション | 概要 |
---|---|
origin | 開始地点 |
destination | 終了地点 |
travelMode | ルーティングの種類 google.maps.DirectionsTravelMode.DRIVING ⇒ 自動車 google.maps.DirectionsTravelMode.TRANSIT ⇒ 電車 google.maps.DirectionsTravelMode.WALKING ⇒ 徒歩 |
waypoints | 経由地点 |
■29行目
DirectionsServiceオブジェクトのrouteメソッドの結果を引数にしてsetDirectionsメソッドを実行することで、地図やパネル上にルート表示できます。
位置、サイズを取得
- 関連クラス
- LatLngクラス:座標(緯度、経度)の情報を保持
- LatLngBoundsクラス:範囲(南西端と北東端)の情報を保持
- 関連メソッド
- MapクラスのgetCenterメソッドで、表示している地図の中心座標をLatLngクラスで取得。
- MapクラスのgetCenterメソッドで、表示している地図の範囲をLatLngBoundsクラスで取得。
- MapクラスのgetZoomメソッドで、表示している地図の縮尺値を取得。
- LatLngBoundsクラスのgetNorthEastメソッドで北東端の座標をLatLngクラスで取得。
- LatLngBoundsクラスのgetSouthWestメソッドで南西端の座標をLatLngクラスで取得。
- LatLngクラスのlatメソッドで緯度を取得。
- LatLngクラスのlngメソッドで経度を取得。
参考・補足
- 公式ドキュメント
- ガイド、リファレンス、サンプル情報を確認できます。
- GoogleMapsAPIの仕様変更について
- 2016年6月22日以降、地図を表示させる場合には、APIキーが必要になりました。
- 一日25,000回の表示を上限としているようです。
- キーの取得は、Google Developers Consoleで行います。