Google Map - Directions

Get instructions between two addresses

by Brian von Konsky

HTML

<script src="https://maps.googleapis.com/maps/api/js"></script>
<!-- Business Web Technology (ISYS3004) -->
<!-- School of Information Systems      -->
<!-- Curtin University                  -->

<!-- See jsfiddle External Resources for google map api reference -->
<!-- to https://maps.googleapis.com/maps/api/js                   -->

<h2> Get Directions </h2>
<p>
    <label>start address: </label>
    <input id="origin" type="text" />
</p>
<p>
    <label>destination address: </label>
    <input id="destination" type="text" />
</p>
<button onclick="calculateRoute()">Directions</button>
<div id="google_map"></div>
<div id="instructions"></div>

CSS

#google_map {
    width: 512px;
    height: 512px;
    background-color: black;
}

#instructions {
    width: 512px;
    height: 512px;
    background-color: white;
}

label {
    display: inline-block;
    width: 100px;
}

JavaScript

// Try getting instructions to go from
// 1. Curtin University, Bentley to Curtin Graduate School of Business, Perth
// 2. Perth Airport to Curtin University, Bentley
// 3. Perth Airport, Domestic to Curtin University, Bentley
// 4. Charles Telfair Institute, Telfair, Moka Mauritius to Port Louis Mauritius

var directionsDisplay;
var directionsService;
var map;
var markers = [ ];
var infowindow;


// Inialise the map centered on the CBS at the Bentley campus of Curtin University
function initMap() {
   
    // Create a LatLng object centered at Curtin
    var curtin= new google.maps.LatLng(-32.003850, 115.894818);
    
    // Specify basic set of map options
    var mapOptions = {
      zoom: 11,
      center: curtin
      }
    
    // Create the new Map object
    map = new google.maps.Map(document.getElementById("google_map"), mapOptions);
    
    // Create a popup information window to display when markers are clicked
    infowindow = new google.maps.InfoWindow({});
    
    // Get an instance of a DirectionsService object
    directionsService = new google.maps.DirectionsService();
    
    // Attach an instance of a DirectionsRenderer object to the map
    directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);
}

// Use Google to get directions between two locations
// and display it on a map
function calculateRoute() {
  
    // Get the origina and destination addresses from teh form
    var origin      = document.getElementById('origin').value;
    var destination = document.getElementById('destination').value;
    
    // Form the request to be sent to google
    var request = {
        origin: origin,
        destination:destination,
        travelMode: google.maps.TravelMode.DRIVING
    };
    
    // Find out how to get there from Google
    directionsService.route(request, function(response, status) {
        // If all is okay, display it on the map
        if (status == google.maps.DirectionsStatus.OK) {
      ...