This example gives you a direction from origin to destination. First adds a search box to a map, using the Google Place Autocomplete feature. People can enter geographical searches. The search box will return a pick list containing a mix of places and predicted search terms. Then sending the search values to google “directionsService” you can get the direction. Then send the api response to “directionsDisplay” to draw the route. DEMO
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13,
mapTypeId: 'roadmap'
});
directionsDisplay.setMap(map);
// Create the search box and link it to the UI element.
var inputO = document.getElementById('pac-input-origin');
var inputD = document.getElementById('pac-input-dest');
searchBoxO = new google.maps.places.SearchBox(inputO);
searchBoxD = new google.maps.places.SearchBox(inputD);
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBoxO.addListener('places_changed', function() {
onChangeHandler();
});
searchBoxD.addListener('places_changed', function() {
onChangeHandler();
});
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var placesO = searchBoxO.getPlaces();
var placesD = searchBoxD.getPlaces();
if (!placesO || !placesD || placesO.length == 0 || placesD.length == 0) {
return;
}
directionsService.route({
origin: {
lat: placesO[0].geometry.location.lat(),
lng: placesO[0].geometry.location.lng()
},
destination: {
lat: placesD[0].geometry.location.lat(),
lng: placesD[0].geometry.location.lng()
},
travelMode: 'DRIVING'
}, function(response, status) {
console.log(response);
document.getElementById("distLen").value = response.routes[0].legs[0].distance.text;
document.getElementById("timeLen").value = response.routes[0].legs[0].duration.text;
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
Like this:
Like Loading...