Can anyone please help. I just need a simple script. I have a form posted to another page. two formfields are:
fromaddress and toaddress
The only thing I need is a script that shows me the distance in km and the time it takes using google maps. I have found dozens of scripts but I cannot get it working. The map is already there with this code which seems to work perfect.
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=AIzaSyDdDwV6_l5n2bS3gM6NBCla3RFLtIFc_HE&sensor=false"></script><script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
var start = "<? echo $_POST[fromaddress]; ?>";
var end = "<? echo $_POST[toaddress]; ?>";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
$(document).ready(function(){
initialize();
});
</script>
But how do i display the distance and the time. Best option is to get it in a php value like:
$distance = some-code;
$time = some-code-too;
Thanks a lot for helping.
You need to use different API for that. First of all, don't use JS but PHP, here's the code snippet that should work for you ;)
Output:
You can calculate the complete route duration and distance by adding up all the legs:
call it like this:
working example