var myLatLng = { lat: 38.736946, lng: -9.142685 };
var mapOptions = {
center: myLatLng,
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Hide result box
document.getElementById("output").style.display = "none";
// Create/Init map
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);
// Create a DirectionsService object to use the route method and get a result for our request
var directionsService = new google.maps.DirectionsService();
// Create a DirectionsRenderer object which we will use to display the route
var directionsDisplay = new google.maps.DirectionsRenderer();
// Bind the DirectionsRenderer to the map
directionsDisplay.setMap(map);
// Define calcRoute function
function calcRoute() {
//create request
var request = {
origin: document.getElementById("location-1").value,
destination: document.getElementById("location-2").value,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
}
// Routing
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Get distance and time
$("#output").html("<div class='result-table'> Driving distance: " + result.routes[0].legs[0].distance.text + ".<br />Duration: " + result.routes[0].legs[0].duration.text + ".</div>");
document.getElementById("output").style.display = "block";
//display route
directionsDisplay.setDirections(result);
} else {
//delete route from map
directionsDisplay.setDirections({ routes: [] });
//center map in London
map.setCenter(myLatLng);
//Show error message
alert("Can't find road! Please try again!");
clearRoute();
}
});
}
// Clear results
function clearRoute(){
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.