Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Google Distance Matrix API Multiple Destinations

    Hi, I have finally worked out the code to make the google distance matrix api work with a form. I can enter in a start and end address and it will provide me with what I want. Now here's the problem.

    What I really want is to have a predetermined start point. Then in the form the user adds a start and end address and after that another predetermined end point.

    Example:

    Origin: MyPlace
    DestinationA: User Input
    DestinationB: User Input
    DestinationC: MyPlace

    Then it should give me the total distance between all 4 points.

    Here's the code I have which works for two user input fields.

    Code:
    var directionDisplay;
    var map;
    
    function initialize() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var tcc = new google.maps.LatLng(30.813187, 75.96298);
        var myOptions = {
            zoom:7,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: tcc
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        directionsDisplay.setMap(map);
    }
    
    var directionsService = new google.maps.DirectionsService();
    
    function calcRoute() {
    $('#panic').empty();
    $('#executive').empty();
    $('#vip').empty();
    $('#regular').empty();
        var start = document.getElementById("start").value;
        var end = document.getElementById("end").value;
    
        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);
    var distanceInput = document.getElementById("distance");
    distanceInput.value = response.routes[0].legs[0].distance.value / 1000;	    
            }
        });	
    }
    Any help would be appreciated!

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,899
    Thanks
    56
    Thanked 542 Times in 539 Posts
    not to be a stickler, but you're actually working with the directions service api - the distance matrix does something similar but different.

    The good news is that the directions service has built-in functionality for what you are trying to do - waypoints

    The basic logic would be: set your start and end points to MyPlace (I'm assuming that would be your tcc variable), then put your intermediary values into an array and feed that to the request. The above example takes any number of waypoints, but being that you only have two, your code would end up looking something like:

    Code:
    var waypts = [
    document.getElementById("destinationA").value, //you may want to add some logic here to validate the inputs
    document.getElementById("destinationB").value
    ];
    
    var request = {
            origin:tcc,
            waypoints: waypts,
            destination:tcc,  //or some other predetermined point
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
    there is also an optimizeWaypoints variable that you can set, which will ensure that the route displayed is the most logical (or at least the shortest distance)

    the above is untested, but it should work - give us a yell if something goes pear-shaped
    Last edited by xelawho; 03-10-2014 at 03:30 PM.

  • Users who have thanked xelawho for this post:

    robsworld78 (03-10-2014)

  • #3
    New to the CF scene
    Join Date
    Dec 2013
    Location
    New Delhi
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Matrix API Software provide wrong shortest distance

  • #4
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Thanks for clearing up what I'm using, I've been trying so much to get this work and now forget what I'm using, lol.

    I tried adding the waypoints to the code but nothing happens when the function is called. Here's what I have. Not sure what you mean by tcc variable?

    Code:
    var directionsService = new google.maps.DirectionsService();
    
    function calcRoute() {
    $('#panic').empty();
    $('#executive').empty();
    $('#vip').empty();
    $('#regular').empty();
        var start = document.getElementById("start").value;
    	var waypts = [
    	"Edmonton, Alberta",
    	"Leduc, Alberta"
    ];
    	var end = document.getElementById("end").value;
    
        var request = {
            origin:start,
            waypoints: waypts,
            destination:end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
    var distanceInput = document.getElementById("distance");
    distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
         }
        });	
    }
    I don't want to optimize the route, I need it to calculate in the set order.

    Thanks for your help!
    Last edited by robsworld78; 03-10-2014 at 08:25 PM.

  • #5
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Lets start fresh...
    Last edited by robsworld78; 03-10-2014 at 10:11 PM.

  • #6
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Ok, well I'm closer but not there, examples are never like they should be. The waypoints in the example are in an option box but that won't work for me as the waypoints need to be entered by the user and the start and end fixed. Oh figured out the tcc variable, lol.

    So my question is how do I convert this option box for the waypoints to 2 text boxes? I have the text boxes setup for start and end but I think its because of the array the waypoint ones aren't working.

    Here's the code I have now, it works fine as it is. It will calculate the total km's between all points and display it.

    How can I change the option box to text boxes? I would call them waypoint1 and waypoint2.

    Code:
    function calcRoute() {
      var start = document.getElementById('start').value;
      var end = document.getElementById('end').value;
      var waypts = [];
      var checkboxArray = document.getElementById('waypoints');
      for (var i = 0; i < checkboxArray.length; i++) {
        if (checkboxArray.options[i].selected == true) {
          waypts.push({
              location:checkboxArray[i].value,
              stopover:true});
        }
      }
    
      var request = {
          origin: start,
          destination: end,
          waypoints: waypts,
          optimizeWaypoints: true,
          travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
    
            computeTotalDistance(response);
          } else {
            alert("directions response "+status);
          }
        });
      }
    
          function computeTotalDistance(result) {
          var totalDist = 0;
          var totalTime = 0;
          var myroute = result.routes[0];
          for (i = 0; i < myroute.legs.length; i++) {
            totalDist += myroute.legs[i].distance.value;
            totalTime += myroute.legs[i].duration.value;      
          }
          totalDist = totalDist / 1000.
          document.getElementById("regular").innerHTML = totalDist + " km<br>" + (totalTime / 60).toFixed(2) + " minutes";
          }
    	  
    google.maps.event.addDomListener(window, 'load', initialize);

  • #7
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,899
    Thanks
    56
    Thanked 542 Times in 539 Posts
    sorry - you're absolutely right. It's been a while since I've done anything google maps and I forgot that waypoints is an array of objects, not just strings. In your last example it would be
    Code:
    var waypts = [
    	{location:"Edmonton, Alberta",stopover:true},
    	{location:"Leduc, Alberta",stopover:true}
    ];
    if you were looking to get the waypoints from user input that would be

    Code:
    var waypts = [
    	{location:document.getElementById("destinationA").value,stopover:true},
    	{location:document.getElementById("destinationB").value,stopover:true}
    ];
    the tcc variable was where you were centering the map in your first post:
    Code:
    var tcc = new google.maps.LatLng(30.813187, 75.96298);

  • Users who have thanked xelawho for this post:

    robsworld78 (03-10-2014)

  • #8
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Hi, I was just posting my results, I figured it out and yeah its what you suggest. Here's my final code.

    Code:
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
        <script>
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    
    function initialize() {
      directionsDisplay = new google.maps.DirectionsRenderer();
      var tcc = new google.maps.LatLng(30.813187, 75.96298);
      var mapOptions = {
        zoom: 6,
        center: tcc
      }
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      directionsDisplay.setMap(map);
    }
    
    function calcRoute() {
      var start = "Edmonton, Alberta";
      var end = "Edmonton, Alberta";
    
      var request = {
          origin: start,
          destination: end,
          waypoints: [
        {
          location: document.getElementById('waypoint1').value,
          stopover:true
        },{
          location: document.getElementById('waypoint2').value,
          stopover:true
        }],
    
          travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
    	  
            computeTotalDistance(response);
          } else {
            alert("directions response "+status);
          }
        });
      }
    
          function computeTotalDistance(result) {
          var totalDist = 0;
          var totalTime = 0;
          var myroute = result.routes[0];
          for (i = 0; i < myroute.legs.length; i++) {
            totalDist += myroute.legs[i].distance.value;
            totalTime += myroute.legs[i].duration.value;      
          }
          totalDist = totalDist / 1000.
          document.getElementById("distance").innerHTML = totalDist + " km<br>" + (totalTime / 60).toFixed(2) + " minutes";
          }
    	  
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •