Distance between two locations in javascript

google-maps, google-maps-api-3, javascript, jquery

Solution

You could use DistanceMatrixService of google map for calculating distance between two points.

The following functions calculates the

function calculateDistances() {
  origin = document.getElementById('source').value; //Get the source string
  destination = document.getElementById('dest').value; //Get the destination string
  var service = new google.maps.DistanceMatrixService(); //initialize the distance service
  service.getDistanceMatrix(
    {
      origins: [origin], //set origin, you can specify multiple sources here
      destinations: [destination],//set destination, you can specify multiple destinations here
      travelMode: google.maps.TravelMode.DRIVING, //set the travelmode
      unitSystem: google.maps.UnitSystem.METRIC,//The unit system to use when displaying distance
      avoidHighways: false,
      avoidTolls: false
    }, calcDistance); // here calcDistance is the call back function
}

Code for callback function calcDistance

function calcDistance(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) { // check if there is valid result
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;

      for (var j = 0; j < results.length; j++) {

        alert ('Distance from '+origins[i] + ' to ' + destinations[j]
            + ': ' + results[j].distance.text ); // alert the result
      }
    }
  }
}

You can find a working demo here

Problem

Can some one help me what went wrong on this code snippet ? My ultimate aim to find distance two locations using googles javascript API . I have used geocomplete jquery function for address autocomplete. On click of search nothing is happening.Im just a beginner please help ``` <!DOCTYPE html> <html> <head> <title>Distance between Two Places</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="styles.css" /> <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script> <script type="text/javascript"> var geocoder, location1, location2; function initialize() { geocoder = new GClientGeocoder(); } function showLocation() { geocoder.getLocations(document.forms[0].address1.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(document.forms[0].address2.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; calculateDistance(); } }); } }); } function calculateDistance() { try { var glatlng1 = new GLatLng(location1.lat, location1.lon); var glatlng2 = new GLatLng(location2.lat, location2.lon); var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1); var kmdistance = (miledistance * 1.609344).toFixed(1); document.getElementById('results').innerHTML = '<strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)'; } catch (error) { alert(error); } } </script> </head> <body onload="initialize()"> <form action="#" onsubmit="showLocation(); return false;"> <input id="geocomplete" type="text" name="address1" placeholder="Type in an address" size="90" /> <input id="geocomplete1" type="text" name="address2" placeholder="Type in an address" size="90" /> <input type="submit" name="find" value="Search" /> </form> <p id="results"></p> <script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="../jquery.geocomplete.js"></script> <script src="logger.js"></script> <script> $(function(){ $("#geocomplete").geocomplete() .bind("geocode:result", function(event, result){ $.log("Result: " + result.formatted_address); }) .bind("geocode:error", function(event, status){ $.log("ERROR: " + status); }) .bind("geocode:multiple", function(event, results){ $.log("Multiple: " + results.length + " results found"); }); $("#geocomplete1").geocomplete() .bind("geocode:result", function(event, result){ $.log("Result: " + result.formatted_address); }) .bind("geocode:error", function(event, status){ $.log("ERROR: " + status); }) .bind("geocode:multiple", function(event, results){ $.log("Multiple: " + results.length + " results found"); }); $("#find").click(function(){ $("#geocomplete").trigger("geocode"); }); $("#examples a").click(function(){ $("#geocomplete").val($(this).text()).trigger("geocode"); return false; }); }); </script> </body> </html> ```

Original source