Using Google Map directions in HTML pages

Friday January 11, 2013 ()

This demonstration uses the DirectionsService JavaScript API of Google Map version 3 to request for the directions.   It uses DirectionsRenderer to display the results instead of handling them ourselves manually.   This demonstration does not use WayPoints.

See the DirectionsService documentation for information and options.

The complete page source of what we describe here can be found near the end of this write-up.   Live demo is also provided here http://demo.kahimyang.info/cgi-cpp/hdirections.html.   This demonstration and the live demo use two panes,  the map pane and the textual directions frame that is hidden initially until a direction response is returned successfully by the API which also resizes the map canvas.

Let us start by loading the Google Map version 3 JavaScript API.

<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&language=ja">
</script>

language parameter is optional but is useful if you want the result displayed to a language of your choice (other than the browser default).   You can also use the region parameter to avail of region biasing.  A region with a value of jp for example will interprete the start and destination values as Japanese locations.

Next, we create DirectionsRenderer and Map objects.  Please see the inline comments for descriptions.

// Our directions renderer and Google Map
var map;
var directionsDisplay;

function initialize() {
    // Make the route draggable
    var rendererOptions = {
         draggable: true
    }
    // Create the DirectionsRenderer object
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

    // Center map to this LatLang
    var manila = new google.maps.LatLng(14.5833, 121.0000);
    var mapOptions = {
        zoom:9,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: manila
    }

    // Create map object with the above options to a div element in the page
    // of id of map_canvass and bind this map to the DirectionsRenderer object
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    directionsDisplay.setMap(map);

    // The div where the textual directions are displayed.  This is hidden
    // initially
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));

}

Submitting the request

To submit a request create an object of type DirectionsService (please consult the documentation for more options).   Call DirectionsService.route() to initiate a request to the Directions service, passing it a DirectionsRequest object containing options and a callback method to execute upon receipt of the response.


var directionsService = new google.maps.DirectionsService();

function calcRoute(start, end) {
    
    // JSON request options
    var request = {
        origin: start,
        destination: end,
        provideRouteAlternatives: true,
        travelMode: google.maps.TravelMode.DRIVING
    };

    //  The request call
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            
            // Resize the map canvas to accomodate
            // the textual directions panel
            
            map_canvas.style.width='70%';
            directionsPanel.style.display='inline';  

            // Request map resize
            google.maps.event.trigger(map, "resize");

            // Display the reponse
            directionsDisplay.setDirections(response);
        }
        else {
            // You may want to handle other return values.  Please
            // see the documentation for the other values.
            alert ('An error has occurred !');
        }
    });
}

response is of type DirectionsResult with a single member, an array of routes of type DirectionsRoute. Use routes [] if you want to dig more into the results. The number of routes (length of array) is controlled by provideRouteAlternatives option. If provideRouteAlternatives is set to false (line 9 above), only one route is returned otherwise, results may contain more than one routes.

Parameters to calcRoute() are values of HTML text input elements of the controls.   Please see the HTML body below.

The HTML page

<body>
    <!-- The controls is a floating frame near the 
    bottom of map
    -->        
    <span id="controls">
        <input id="start" placeholder="Start" />
        <input id="end" placeholder="Destination" />            
        <button onclick="showDirectionsPanelandCalculate();return false">
            Get directions
        </button>            
    </span>
    <!-- Map canvas -->
    <div id="map_canvas">
<!-- Directions in text --> <div id="directionsPanel"> <button onclick="hideDirectionsPanel();return false;">Hide</button> </div> </body>

showDirectionsPanelandCalculate() in line 8, is a support function that calls calcRoute(start, end).   hideDirectionsPanel() (line 16) hides the text panel and resizes the map canvas.   See the complete page source below for more of those functions.

The complete page

<!DOCTYPE html>
<html>
    <head>
        <title>Google Directions</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false">
        </script>

        <script type="text/javascript">
            var map;
            var directionsDisplay;
            var directionsService = new google.maps.DirectionsService();

            function initialize() {
                // Make the route draggable
                var rendererOptions = {
                    draggable: true
                } 
                directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
                var manila = new google.maps.LatLng(14.5833, 121.0000);
                var mapOptions = {
                    zoom:9,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    center: manila
                }
                map = 
                 new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
                directionsDisplay.setMap(map);
                directionsDisplay.setPanel(document.getElementById("directionsPanel"));
            }
            
            function calcRoute(start, end) {

                var request = {
                    origin:start,
                    destination:end,
                    provideRouteAlternatives: true,
                    travelMode: google.maps.TravelMode.DRIVING
                };
                
                directionsService.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {   
                        
                        // Resize the map canvas to accomodate
                        // the textual directions panel
                        map_canvas.style.width='70%';
                        directionsPanel.style.display='inline';  
                        // Request map resize.
                        google.maps.event.trigger(map, "resize");
                                                
                        // display the directions
                        directionsDisplay.setDirections(response);
                    }
                    else {                      
                       alert ('An error has occurred !'); 
                    }

                });                              
            }
            
            /*
             * Show the textual directions panel, resize the map canvas
             * trigger resize event on map, and compute the directions             
             * Note that start and end corresponds to the input id of
             * the controls
             */
            function showDirectionsPanelandCalculate () {  
                if (start.value.length==0 || end.value.length==0) {
                    return;
                }                 
                calcRoute (start.value,end.value);
               
            }
            
            /*
             * Hide the textual directions panel resize map
             * canvas to original size, trigger resize on
             * map.  You can also recalculate directions if
             * desired.
             */
            function hideDirectionsPanel () {
                                
                map_canvas.style.width='100%';
                directionsPanel.style.display='none';
                google.maps.event.trigger(map, "resize");

            }        
            
            google.maps.event.addDomListener(window, 'load', initialize);
                      
        </script>  

        <style>
            body {
                width:950px;
            }
            /* Controls that takes the start/end address.
            */
            #controls {
                background-color: lightgray;
                font-size: 11px;
                position:fixed;
                bottom:-0px;
                margin-bottom: 20px;
                left:5px;border:1px solid darkgray;
                padding:5px;
                z-index:10000;
            }
            /*  Map canvas */
            #map_canvas {
                float:left;
                width:100%; 
                height:700px;                
            }

            /*  Textual directions frame */
            #directionsPanel {
                float:right;
                display: none;
                width:29%;
                height: 700px;
                font-size: 12px; 
                margin-left: 2px;
                overflow: scroll;
            }
        </style>
    </head>

    <body>
        <!-- 
           The controls are in a floating frame near the 
           bottom of map
        -->        
        <span id="controls">
            <input id="start" placeholder="Start" />
            <input id="end" placeholder="Destination" />            
            <button onclick="showDirectionsPanelandCalculate();return false">
                Get directions
            </button>            
        </span>
        <!-- Map canvas -->
        <div id="map_canvas"></div>  
        <!-- Directions in text -->
        <div id="directionsPanel"> 
            <button onclick="hideDirectionsPanel();return false;">Hide</button>
        </div> 
    </body>
</html>

If you find this code helpful and wanted to use it in your project, just copy the code above and then tailor it more to your needs.

That's it Good Luck.


3,888

Comments (Using Google Map directions in HTML pages)





Share icon