Directions Service
Today I am going to discuss on a very interesting topic of google map.How will you implement direction service in google map.If you want to see the direction from one place to another place, then follow the code.
Step 1
First of all we are loading the map inside a div element with id yourmap.Adding some style for the map.Here also we add two input element for getting source and destination.When we will click on the button, we will see the direction from source to destination.
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#yourmap {
height: 99%;
width: 99%;
}
</style>
<div id=”yourmap”></div>
To load the map you have use google map api.You also have to generate api key for that.
async defer></script>
Generate you api key from here API key .
You must have to be login in google for that.
After generating api key , add your key into the script url as parameter.Now here we are adding a callback function into the script parameter with name loadMap.
Step 2
Now we are declare the callback function.Here we are also loading the direction service.After entering location and click on the button, you will see the direction.
{
var lat_lang = {lat: 22.2872402, lng: 87.7441941};
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById(‘yourmap’), { zoom: 10, center: lat_lang });
directionsDisplay.setMap(map);
var onClickHandler = function() { calculateAndDisplayRoute(directionsService, directionsDisplay); };
document.getElementById(‘mybtn’).addEventListener(‘click’, onClickHandler);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay)
{
directionsService.route({ origin: document.getElementById(‘source’).value, destination: document.getElementById(‘destination’).value, travelMode: google.maps.TravelMode.DRIVING }, function(response, status) { if (status === google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } else { window.alert(‘Request for getting direction is failed due to ‘ + status); } });
}
That’s all.