javascriptgoogle-mapsgoogle-maps-api-3

Distance between markers Google maps


I'm trying to show distance between markers but It is showing just distance between some markers not all of them.Here is my code The function below let me to display distance. Can everyone help me or give me an example to resolve it?

function drawRouteMap(locations) {

    var start, end;
    var waypts = [];

    for (var k = 0; k < locations.length; k++) {
        if (k >= 1 && k <= locations.length - 2) {
            waypts.push({
                location: locations[k],
                stopover: true
            });
        }
        if (k == 0) start = locations[k];

        if (k == locations.length - 1) end = locations[k];

    }
    var request = {
        origin: start,
        destination: end,
        waypoints: waypts,
        optimizeWaypoints: false,
        travelMode: google.maps.TravelMode.DRIVING
    };
    console.log(request);

    directionsService.push(new google.maps.DirectionsService());
    var instance = directionsService.length - 1;
    directionsDisplay.push(new google.maps.DirectionsRenderer({
        preserveViewport: true
    }));
    directionsDisplay[instance].setMap(map);
    directionsService[instance].route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            console.log(status);
  directionsDisplay[instance].setDirections(response);
            var f = response.routes[0];

      
            var summaryPanel = document.getElementById("directions_panel");
            summaryPanel.innerHTML = "";
            // For each route, display summary information.
            for (var i = 0; i < f.legs.length; i++) {
                var routeSegment = i + 1;
               summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
          
                summaryPanel.innerHTML += f.legs[i].distance.text + "<br /><br />";
            }
             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("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}


Solution

  • You are overwriting the route segments, total distance and time for each route. If you want the total for the combination of all the individual routes that are being combined to overcome the waypoints restriction on the Google Maps Javascript API v3 (free version), you need to combine the "routes" as well as the legs of each route.

    function drawRouteMap(locations) {
        var start, end;
        var waypts = [];
        for (var k = 0; k < locations.length; k++) {
            if (k >= 1 && k <= locations.length - 2) {
                waypts.push({
                    location: locations[k],
                    stopover: true
                });
            }
            if (k == 0) start = locations[k];
    
            if (k == locations.length - 1) end = locations[k];
    
        }
        var request = {
            origin: start,
            destination: end,
            waypoints: waypts,
            optimizeWaypoints: false,
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.push(new google.maps.DirectionsService());
        var instance = directionsService.length - 1;
        directionsDisplay.push(new google.maps.DirectionsRenderer({
            preserveViewport: true
        }));
        directionsDisplay[instance].setMap(map);
        directionsService[instance].route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay[instance].setDirections(response);
                var f = response.routes[0];
                var summaryPanel = document.getElementById("directions_panel");
                // For each route, display summary information.
                for (var i = 0; i < f.legs.length; i++) {
                   routeSegment += 1;
                   summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
              
                   summaryPanel.innerHTML += f.legs[i].distance.text + "<br /><br />";
                }
                computeTotalDistance(response);
            } else {
                alert("directions response " + status);
            }
        });
    }
    var totalDist = 0;
    var totalTime = 0;
    function computeTotalDistance(result) {
        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;
        }
        document.getElementById("total").innerHTML += "total distance is: " + (totalDist/1000).toFixed(2) + " km &nbsp;total time is: " + (totalTime / 60).toFixed(2) + " minutes<br>";
    }
    

    updated fiddle

    code snippet:

    var directionsDisplay = [];
    var directionsService = [];
    var map = null;
    var g = [];
    var path = new Array();
    var routeSegment = 0;
    
    function calcRoute() {
      var msg = [
        '33.7489423024  ,130.7256859226',
        '33.7479701778  ,130.7253248863',
        '33.7482757584  ,130.7286301533',
        '33.7443595228  ,130.7293247203',
        '33.7404432614  ,130.7285471875',
        '33.7368881031  ,130.7295194927',
        '33.7334162726  ,130.7306862223',
        '33.7312776983  ,130.7356025791',
        '33.7320832066  ,130.7378245797',
        '33.7322498889  ,130.7397410796',
        '33.7312500414  ,130.7423520199',
        '33.7301668637  ,130.7446296584',
        '33.7275282876  ,130.7463796345',
        '33.7237787430  ,130.7494906599',
        '33.7228899846  ,130.7515183102',
        '33.7221679037  ,130.7551847057',
        '33.7266397281  ,130.7597952280',
        '33.7323613364  ,130.7596838626',
        '33.7323613364  ,130.7596838626',
        '33.7323613364  ,130.7596838626',
        '33.7323613364  ,130.7596838626',
        '33.7348055151  ,130.7594337709',
        '33.7355555217  ,130.7644055456',
        '33.7437213571  ,130.7668216356',
      ];
      var input_msg = msg;
      var locations = new Array();
    
    
      var bounds = new google.maps.LatLngBounds();
      for (var i = 0; i < input_msg.length; i++) {
        var tmp_lat_lng = input_msg[i].split(",");
        //var s = new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]);
        locations.push(new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]));
        bounds.extend(locations[locations.length - 1]);
      }
    
      var mapOptions = {
        // center: locations[0],
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
      map.fitBounds(bounds);
      var summaryPanel = document.getElementById("directions_panel");
      summaryPanel.innerHTML = "";
      var i = locations.length;
      var index = 0;
    
      while (i != 0) {
    
        if (i < 3) {
          var tmp_locations = new Array();
          for (var j = index; j < locations.length; j++) {
            tmp_locations.push(locations[index]);
          }
          drawRouteMap(tmp_locations);
          i = 0;
          index = locations.length;
        }
    
        if (i >= 3 && i <= 10) {
          console.log("before :fun < 10: i value " + i + " index value" + index);
          var tmp_locations = new Array();
          for (var j = index; j < locations.length; j++) {
            tmp_locations.push(locations[j]);
          }
          drawRouteMap(tmp_locations);
          i = 0;
          index = locations.length;
          console.log("after fun < 10: i value " + i + " index value" + index);
        }
    
        if (i >= 10) {
          console.log("before :fun > 10: i value " + i + " index value" + index);
          var tmp_locations = new Array();
          for (var j = index; j < index + 10; j++) {
            tmp_locations.push(locations[j]);
          }
          drawRouteMap(tmp_locations);
          i = i - 9;
          index = index + 9;
          console.log("after fun > 10: i value " + i + " index value" + index);
        }
      }
    }
    
    
    function drawRouteMap(locations) {
    
      var start, end;
      var waypts = [];
    
      for (var k = 0; k < locations.length; k++) {
        if (k >= 1 && k <= locations.length - 2) {
          waypts.push({
            location: locations[k],
            stopover: true
          });
        }
        if (k == 0) start = locations[k];
    
        if (k == locations.length - 1) end = locations[k];
    
      }
      var request = {
        origin: start,
        destination: end,
        waypoints: waypts,
        optimizeWaypoints: false,
        travelMode: google.maps.TravelMode.DRIVING
      };
      console.log(request);
    
      directionsService.push(new google.maps.DirectionsService());
      var instance = directionsService.length - 1;
      directionsDisplay.push(new google.maps.DirectionsRenderer({
        preserveViewport: true
      }));
      directionsDisplay[instance].setMap(map);
      directionsService[instance].route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          console.log(status);
          directionsDisplay[instance].setDirections(response);
          var f = response.routes[0];
    
          // g=g.concat(f);
          var summaryPanel = document.getElementById("directions_panel");
          // summaryPanel.innerHTML = "";
          // For each route, display summary information.
          for (var i = 0; i < f.legs.length; i++) {
            routeSegment += 1;
            summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
    
            summaryPanel.innerHTML += f.legs[i].distance.text + "<br /><br />";
          }
          computeTotalDistance(response);
        } else {
          alert("directions response " + status);
        }
    
    
    
    
      });
    }
    var totalDist = 0;
    var totalTime = 0;
    
    function computeTotalDistance(result) {
    
      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;
      }
    
      document.getElementById("total").innerHTML += "total distance is: " + (totalDist / 1000).toFixed(2) + " km &nbsp;total time is: " + (totalTime / 60).toFixed(2) + " minutes<br>";
    }
    
    
    
    google.maps.event.addDomListener(window, 'load', calcRoute);
    html,
    body,
    #dvMap {
      height: 70%;
      width: 100%;
    }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="info"></div>
    <div id="dvMap"></div>
    <div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
    <div id="total"></div>
    <div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">