Google Maps – calculate distance between two locations

Forums General discussion Google Maps – calculate distance between two locations

Viewing 6 reply threads
  • Author
    Posts
    • #13071
      Alexander Bautz
      Keymaster

      This example shows an example of how to calculate the distance between two locations. It requires you to get an API key (free for up to 2500 request per day) from here: https://developers.google.com/maps/documentation/javascript/distancematrix

      Unfortunately you cannot use ajax to access the service so you need to use code like this to get it working (adapted from the example provided by Google):

      <script type="text/javascript">
      function init_metrix() {
          var origin = {lat: 59.267711, lng: 10.408090};
          var destination = {lat: 59.911096, lng: 10.7502634};
          var service = new google.maps.DistanceMatrixService;
          service.getDistanceMatrix({
              origins: [origin],
              destinations: [destination],
              travelMode: 'DRIVING',
              unitSystem: google.maps.UnitSystem.METRIC,
              avoidHighways: false,
              avoidTolls: false
          }, function(response, status) {
              if (status !== 'OK') {
                  alert('Error was: ' + status);
              } else {
                  for (var i = 0; i < response.originAddresses.length; i++) {
                      var results = response.rows[i].elements;
                      for (var j = 0; j < results.length; j++) {
                          console.log("From: " + response.originAddresses[i]);
                          console.log("To " + response.destinationAddresses[j]);
                          console.log("Distance (text): " + results[j].distance.text);
                          console.log("Distance (value): " + results[j].distance.value);
                          console.log("Duration (text): " + results[j].duration.text);
                          console.log("Duration (value): " + results[j].duration.value);
                      }
                  }
              }
          });
      }
      </script>
      <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR API KEY&callback=init_metrix"></script>

      Change “YOUR API KEY” for your private API code acquired from the link in the top of this post.

    • #13080
      HYM
      Participant

      Mr.Alexander,if I have a list in sharepoint containing 2 different locations and I want to make a workflow to calculate the distance between them you have any idea about it?

    • #13109
      Alexander Bautz
      Keymaster

      I’m not sure how you can use a workflow, but you can make it work in a list view by adding a CEWP above the list view with this code (replace YOUR API CODE with your own Google Maps API code):

      <script   src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
      <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR API CODE"></script>
      <script type="text/javascript">
      function calcDist(elm,o) {
          if(o.length === 3){
              $(elm).replaceWith("invalid data");
              return;
          }
          var arr = o.split("|");
          var origin = {lat: Number(arr[0]), lng: Number(arr[1])};
          var destination = {lat: Number(arr[2]), lng: Number(arr[3])};
          var service = new google.maps.DistanceMatrixService;
          service.getDistanceMatrix({
              origins: [origin],
              destinations: [destination],
              travelMode: 'DRIVING',
              unitSystem: google.maps.UnitSystem.METRIC,
              avoidHighways: false,
              avoidTolls: false
          }, function(response, status) {
              if (status !== 'OK') {
                  alert('Error was: ' + status);
              } else {
                  for (var i = 0; i < response.originAddresses.length; i++) {
                      var results = response.rows[i].elements;
                      for (var j = 0; j < results.length; j++) {
                          $(elm).replaceWith(results[j].distance.text);
                          // console.log("From: " + response.originAddresses[i]);
                          // console.log("To " + response.destinationAddresses[j]);
                          // console.log("Distance (text): " + results[j].distance.text);
                          // console.log("Distance (value): " + results[j].distance.value);
                          // console.log("Duration (text): " + results[j].duration.text);
                          // console.log("Duration (value): " + results[j].duration.value);
                      }
                  }
              }
          });
      }
      </script>

      Then create a calculated column in your list view with a formula like this:

      ="<img src='/_layouts/15/images/gears_anv4.gif' style='height:16px' onload=calcDist(this,'"&OriginLat&"|"&OriginLong&"|"&DestinationLat&"|"&DestinationLong&"')>"

      Change “OriginLat”, “OriginLong”, “DestinationLat” and “DestinationLong” with your own field names.

      IMPORTANT:
      Under “The data type returned from this formula is:” you must select “Number”. This fools SharePoint to render the image tag as an actual image an not as text.

      Please note that the calculation will be performed on every page load and will not be saved to the list items.

      Hope this helps you on the way.

      Best regards,
      Alexander

    • #13111
      HYM
      Participant

      Hmmm okay thanks thats worked for me.
      Another question if i have in my list another 2 columns source and destination i want to get their latitude and longitude and the results want to fill them in their fields(“OriginLat”, “OriginLong”, “DestinationLat” and “DestinationLong”)in this case if i dont have latitude and longitude of a location i will have it so i can use the results of latitude and longitude to calculate the distance.
      any idea about that?

    • #13162
      Alexander Bautz
      Keymaster

      Sorry for the delay – you can use Google maps – just find the location and look at the URL to see the lat / long. You can also use this website: http://www.latlong.net/

      Alexander

    • #13489
      HYM
      Participant

      Mr.Alexander do you have any idea why calculate distance between 2 locations is working on google chrom and ON IE is not working?

    • #13500
      Alexander Bautz
      Keymaster

      Not sure what could cause this, but if it is an older version of IE it could be some incompatibility. Try bringing up the dev console (hit F12 > Console) to look for errors there.

      Alexander

Viewing 6 reply threads
  • You must be logged in to reply to this topic.