Google Maps Routing Options

Includes Transit

by luissanchezm86

HTML

<script src="http://maps.google.com/maps/api/js?sensor=false&amp;.js"></script>
<input type="text" id="routeFrom" name="routeFrom" value="700 n tryon st, charlotte nc" />
<label for="routeFrom">From</label>
<br />
<input type="text" id="routeTo" name="routeTo" value="Huntersville, NC" />
<label for="routeTo">To</label>
<br />
<select id="routeMode" name="routeMode">
    <option value="DRIVING">Driving</option>
    <option value="WALKING">Walking</option>
    <option value="BICYCLING">Bicycling</option>
    <option value="TRANSIT">Transit</option>
</select>
<label for="routeMode">Mode</label>
<br />
<div class="textcenter">
    <button id="routeGo">Route</button>
    <button id="routeClear">Clear Route</button>
</div>
<div id="map_canvas"></div>
<div id="directions"></div>

CSS

#map_canvas {
    width: 60%;
    height: 400px;
    border: 1px solid black;
    float: left;
}
#directions {
    width: 38%;
    float: right;
}
body {
    font-size: 12px;
}

JavaScript

var directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true
});
var directionsService = new google.maps.DirectionsService();
var map;

$(window).load(function () {
    var myOptions = {
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(35.270, -80.837)
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directions"));

    $("#routeMode").on("change", function () {
        calcRoute();
    });
    $("#routeGo").on("click", function () {
        calcRoute();
    });
    $("#routeClear").on("click", function () {
        directionsDisplay.setDirections({
            routes: []
        });
    });

});


function calcRoute() {
    var request = {
        origin: $("#routeTo").val(),
        destination: $("#routeFrom").val(),
        travelMode: google.maps.TravelMode[$("#routeMode").val()]
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}