Driving Distance Calculator using Google Maps API

I had a post on Google Drive API few days back, It was just an introduction to Google Drive API and yesterday I got an opportunity to taste Google Maps API for the first time. The problem was We had to calculate Distance between two points and then send it to the database using django framework (django work was not done by me as I don't know anything about it). My task was to just get the distance and store it in a variable, and send it via form. Creating the front end application for distance calculator is very easy and even beginner with intermediate knowledge of HTML and Javascript can create it in just few minutes.


  1. First you create a form to get the distance, start and end values.
  2. Then you create an initialize function that initializes the map, for showing direction we have a function from Google Maps API called new google.maps.DirectionsRenderer()
  3. As we are going for driving distance the map type would be roadmap.
  4. Then you create a calcroute function and through using google maps API's variable you get the value. The variable we used from Google Maps API was response.routes[0].legs[0].distance.value 
  5. Now you can do anything with this variable, send it to another page using php or handle it using django., the above API call calculates the distance and can be used anyhow.  


<html>
    <head>
        <title>Distance Calculator</title>
        <style type="text/css">
            #map_canvas {
                height: 100%;
            }
        </style>

         <!-- following code lines add the map to screen -->

        meta name="viewport" content="initial-scale=1.0, user-  scalable=no"/>
        <script type="text/javascript">     src="http://maps.google.com/maps/api/js?sensor=false"></script>
         <!---------- map to screen code ends here -->

         <!--- Initialize maps using javascript -->
         <script type="text/javascript">
var directionDisplay;
var map;

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    <!-- DirectionsRenderer() function draws the directions -->
    var tcc = new google.maps.LatLng(30.813187, 75.96298);
    var myOptions = {
        zoom:7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
     <!-- for driving distance we will use ROADMAP as maptype -->
        center: tcc
     <!-- the center of the map should be tcc -->
    }
<!-- following lines initializes map object that would show in div id map_canvas-->
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
}

<!-- Maps initialization javascript code ends -->

<!-- Now we will calculate the distance between two points -->


var directionsService = new google.maps.DirectionsService();

function calcRoute() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;

    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    <!-- calling google maps API function route to show (highlight) the route from one place to another --> 
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
<!-- This calculates the distance between two points-->
var distanceInput = document.getElementById("distance");
distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
        
        }
    });
}

</script>
         
    </head>
    <body onload="initialize()">
        <div>
            <p>
                <label for="start">Start: </label>
                <input type="text" name="start" id="start" />

                <label for="end">End: </label>
                <input type="text" name="end" id="end" />

                <input type="submit" value="Calculate Route" onclick="calcRoute()">
            </p>
            <p>
                <label for="distance">Distance (km): </label>
                <input type="text" name="distance" id="distance" readonly="true" />
            </p>
        </div>
        <div id="map_canvas"></div>
    </body>
</html>




6 comments:

  1. Runningmap is an easy-to-use route mapping site for runners and outdoor enthusiasts. Plan your training by creating route maps and view the distance between major cities.

    ReplyDelete
  2. Thankls for the tips, A know a cool site for those of you wanting to calculate your journey between two places www.DistanceCalculator.co.za

    ReplyDelete
  3. Whereas i just developed within your web site fire wood but putting in comprehension just a bit reach submits. Decent technique for future, We've been book-marking down length see choices deliberate on spgs process all the way up. distance calculator UK

    ReplyDelete
  4. This blog website is pretty cool! How was it made ! entfernung

    ReplyDelete
  5. Al Rayyan is a city in Qatar located west of Doha, the capital.
    According to legend, the city was named for the sweetness of the water that flowed from the depths of its grounds.
    The following landmarks may be found in Qatar's Al Rayyan city:
    Khalifa International Stadium is part of Aspire Sports City, which features some of Qatar's most well-known teams, including Al Rayyan, Al Sadd, Al Sailiya, and Muaither.
    Most of the princely headquarters, such as the Emirate's Ruler's Council and the royal family's palaces, are located in Al Rayyan, which is considered the major seat of the Qatari government.
    There are several localities in Al-Rayyan, including Al-Sailiya, Al-Wajbah, Al-Shahaniya, and others.
    It also has a number of important initiatives, such as the Qatar Foundation for Education, Science, and Community Development's Education City, which houses a number of institutions and institutes connected with the Qatar Foundation for Education, Science, and Community Development.
    The city is well-known for its numerous water wells and vast agricultural grounds.

    ReplyDelete
  6. Thank you for this post. But It seems that I need an API key for Google Maps. Where I can get it?

    ReplyDelete