【JavaScript実践】 Google Map上に2点間の経路を表示する

この記事では以下の画面を作成する。

f:id:kosumoro:20161002221813j:plain

2点の座標を指定し、座標間の移動経路を描画する。

https://cosmology233.github.io/sandbox/hatena/2016/09/30/

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
  <link rel="stylesheet" href="./styles/style.css">
  <title>Practice JavaScript</title>
</head>
<body>
  <div id="gmap" class="gmap"></div>
  
  <script src="./scripts/script.js"></script>
  <script src="//maps.googleapis.com/maps/api/js?key=AIzaSyBAVKOgsqfbsINYt2qjoLMziacVp6N8zBY&callback=initMap"></script>
</body>
</html>

styles/style.css

body {
  margin: 0; padding: 0;
}

.gmap {
  margin: 0; padding: 0;
  width: 100%; height: 100vh;
}

scripts/script.js

function initMap() {
  var container = document.getElementById("gmap");
  var map = new google.maps.Map(container);
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer();
  
  map.setOptions({
    "zoom": 13,
    "center": {
      "lat": 34.647,
      "lng": 35.513
    }
  });
  
  directionsDisplay.setMap(map);
  
  directionsService.route({
    "travelMode": google.maps.TravelMode.DRIVING,
    "origin": {
      "lat": 34.647,
      "lng": 135.513
    },
    "destination": {
      "lat": 34.693,
      "lng": 135.502
    }
  }, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
    else {
      window.alert("Failed: " + status);
    }
  });
}