Calculate Distance between two points google maps javascript

Calculate Distance between two points google maps javascript

Calculate Distance between two points google maps javascript : 

This post help You for calculating distance of two point wit auto fill location. This is using google api,javascript,and jquery.Downloads code here free and impliment your project and enjoy.

For Live you need api its free

click for Your api key  --- https://developers.google.com/maps/documentation/javascript/get-api-key

and create index.php put this code


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Calculate Distance between two points google maps javascript</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 
  <!------- for local server only --------->
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
 
 <!------------
 for live server only
   <script src="//maps.googleapis.com/maps/api/js?key=your-api-key&sensor=false&libraries=places" type="text/javascript"></script>
 ------------->
 
</head>
<body>


<div class="container">
  <h2>Calculate Distance between two points google maps javascript</h2>

  <form class="form-inline" action="">
    <div class="form-group">
      <label for="email">Source:</label>
      <input type="text" class="form-control" id="source" value="New Delhi, Delhi, India" >
    </div>
    <div class="form-group">
      <label for="pwd">Destination:</label>
      <input type="text" class="form-control" id="destination" value="Delhi Cantt, New Delhi, Delhi, India" >
    </div>

    <button type="button" value="Get Route" onclick="get_rout()" >Get Rout & Distance</button>
    
    <div class="form-group">
      <label for="pwd">Distance in km :</label>
      <input type="text" class="form-control distance" readonly >
    </div>
  </form>
 
  <div class="row" >
  <br /><br />
  <div class='col-md-6' id='maplocation' style="height: 450px;" ></div>
  <div class='col-md-6' id='panallocation' style="width: 500px; height: 500px" ></div>
  </div>
</div>

 

 

<script type="text/javascript">
        var source, destination;
        var darection = new google.maps.DirectionsRenderer;
        var directionsService = new google.maps.DirectionsService;
        google.maps.event.addDomListener(window, 'load', function () {
            new google.maps.places.SearchBox(document.getElementById('source'));
            new google.maps.places.SearchBox(document.getElementById('destination'));
            
        });

        function get_rout() {


            var mapOptions = {
                mapTypeControl: false,
                center: {lat: -33.8688, lng: 151.2195},
                zoom: 13
            };
            
            map = new google.maps.Map(document.getElementById('maplocation'), mapOptions);
            darection.setMap(map);
            darection.setPanel(document.getElementById('panallocation'));


            source = document.getElementById("source").value;
            destination = document.getElementById("destination").value;

            var request = {
                origin: source,
                destination: destination,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    darection.setDirections(response);
                }
            });


            
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix({
                origins: [source],
                destinations: [destination],
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            }, function (response, status) {
                if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                    var distance = response.rows[0].elements[0].distance.text;
                    var duration = response.rows[0].elements[0].duration.text;
                    
                    distancefinel = distance.split(" ");
                    $('.distance').val(distancefinel[0]);
                    
                    
                    
                } else {
                    alert("Unable to find the distance via road.");
                }
            });
        }
        
        
        
        
    </script>

 

</body>
</html>

 

 

Demo

Download Hare

Total Coments (9)

  1. rummaan
    • 24 Jan 2018

    it is not working

  2. rummaan
    • 24 Jan 2018

    how to run in my local server

  3. sudip pyne
    • 29 Jan 2018

    / / / HOW TO CALCULATE DISTANCE BETWEEN TWO PLACE USING JAVASCRIPT //// <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Geocoding service</title> [removed][removed] [removed][removed] [removed] function codeAddress() { var s1,s2,d1,d2,p1,p2; var address1 = document.getElementById("address1").value; var address2 = document.getElementById("address2").value; var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address1}, function(results, status) { var location = results[0].geometry.location; s1=location.lat(); s2=location.lng(); //alert(s1); //alert(s2); p1 = new google.maps.LatLng(s1, s2); }); geocoder.geocode( { 'address': address2}, function(results, status) { var location = results[0].geometry.location; d1=location.lat(); d2=location.lng(); //alert(d1); //alert(d2); p2 = new google.maps.LatLng(d1, d2); alert((google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2)); }); google.maps.event.addDomListener(window, 'load', codeAddress); } [removed] </head> <body>

    <input id="address1" type="textbox" value=""> <input id="address2" type="textbox" value=""> <input type="button" value="Geocode" onclick="codeAddress()"> <input type="button" value="Geocode" onclick="calcDistance()">
    </body> </html>

  4. sudip pyne
    • 29 Jan 2018

    [removed][removed] [removed][removed] in place of removed

  5. Alex
    • 30 Jan 2018

    To work put this in your header section [removed][removed]

  6. Alex
    • 30 Jan 2018

    [removed]</ script>

  7. Alex
    • 30 Jan 2018

    I can't put the script here but look in this tutorial you will find (in head section) a script with this source: /maps .googleapis.com/ maps. You have to copy that in your file and replace key=your-api-key with key=your generated api key (look above in this tut for a link).

  8. Roland
    • 04 Feb 2018

    Can you please tell me 1.how to get result in Miles 2. If I put my google api key in [removed][removed] This script stops working. Can you please check and help? Thanks very much

  9. Marko
    • 08 Feb 2018

    Hi, I would like to know for this script if you can simply calculate the distance as the crow flies. Thank you