Contents |
Google Maps API(Google Maps JavaScript API)で経路案内機能を作ってみます。
今回は、渋谷駅から東京スカイツリーまでの経路案内をします。
・ APIキー
→ このサイト等を参照に取得すること
・ 出発地点、目的地の緯度と経度
→ このサイト等で取得できます。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>GoogleMapsAPIテスト</title>
</head>
<body>
<p>以下に地図を表示</p>
<div id="map" style="width:620px; height:400px">
</div>
<script type="text/javascript">
function initMap () {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
// mapの表示時の中心点を決めている(ルート案内に失敗したときのデフォルト画面)
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(35.658034, 139.701636)
}
// mapの表示
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
// directionServiceに渡す変数
// 出発地点、目的地、移動方法等を定義する
var request = {
origin: new google.maps.LatLng(35.658034, 139.701636),
destination: new google.maps.LatLng(35.709984,139.810703),
travelMode: google.maps.TravelMode.WALKING
}
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YourAPIKey&callback=initMap"></script>
</body>
</html>
※ YourAPIKeyの部分を取得した自分の鍵に変えてください
結果として、以下のように渋谷からスカイツリーまでの経路情報が表示されます。
経由地がある場合、requestするjsonにwaypoint
を追加します。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>GoogleMapsAPIテスト</title>
</head>
<body>
<p>以下に地図を表示</p>
<div id="map" style="width:620px; height:400px">
</div>
<script type="text/javascript">
function initMap () {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
// mapの表示時の中心点を決めている(ルート案内に失敗したときのデフォルト画面)
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(35.658034, 139.701636)
}
// mapの表示
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
// directionServiceに渡す変数
// 出発地点、目的地、移動方法等を定義する
// 経由地を設定する場合は、waypointsを追加する
var request = {
origin: new google.maps.LatLng(35.658034, 139.701636),
destination: new google.maps.LatLng(35.709984,139.810703),
waypoints: [
{
location: new google.maps.LatLng(35.689409, 139.700129)
}],
travelMode: google.maps.TravelMode.WALKING
}
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YourAPIKey&callback=initMap"></script>
</body>
</html>
※ YourAPIKeyの部分を取得した自分の鍵に変えてください
結果として、渋谷から新宿を経由してスカイツリーまでの経路情報が表示されます。