Google Maps API: Total distance with waypoints - javascript

I'm trying to calculate the total distance for a route with a single waypoint in it, but somehow my code only returns the distance to the first waypoint instead of the total distance.
Here's my code:
function calcRoute(homebase,from,to,via){
var start = from;
var end = to;
var wypt = [ ];
wypt.push({
location:via,
stopover:true});
var request = {
origin:start,
destination:end,
waypoints:wypt,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.DirectionsUnitSystem.METRIC
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var distance = response.routes[0].legs[0].distance.text;
var time_taken = response.routes[0].legs[0].duration.text;
var calc_distance = response.routes[0].legs[0].distance.value;
}
});
}

The reason you only get the distance for legs[0] is because that is what your code is calculating. You need to sum up the distances of all the legs:
http://www.geocodezip.com/v3_GoogleEx_directions-waypoints_totalDist.html
code snippet:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
calcRoute();
}
google.maps.event.addDomListener(window, 'load', initialize);
function calcRoute() {
var request = {
// from: Blackpool to: Preston to: Blackburn
origin: "Blackpool,UK",
destination: "Blackburn,UK",
waypoints: [{
location: "Preston,UK",
stopover: true
}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.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";
}
html {
height: 100%
}
body {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="total"></div>
</div>

Related

How to calculate total distance and time (getDistanceMatrix)

I need to get total distance and travel time with service.getDistanceMatrix({, sum A + B + C + D = total distance.
The way that i try, only i get the first calculate, but I need to get the sum alls points for show to user total-distance
The below attach the image with sample of web
SAMPLE IMAGE
My JavaScript code
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
// P1
var stop;
var markers = [];
var waypts = [];
var pardas = ["6.347033,-75.559017","6.348764,-75.562970","6.334624,-75.556157"];
stop = new google.maps.LatLng(6.347033, -75.559017)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(6.348764, -75.562970)
waypts.push({
location: stop,
stopover: true
});
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false,
});
window.onload=function(){
function initialize() {
//P2
var mapOptions = {
zoom: 15,
//center: new google.maps.LatLng(6.3490548, -75.55802080000001),
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//calcRoute();
}
source = new google.maps.LatLng(6.3490548, -75.55802080000001);
destination = new google.maps.LatLng(6.334624, -75.556157);
//P3
function calcRoute() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
createMarker(source, 'source', false);
createMarker(destination, 'destination', false);
var route = response.routes[0];
for (var i = 1; i < route['legs'].length; i++) {
console.log(route['legs'][i].start_location.toString(), waypts[i - 1].location.toString());
waypts[i - 1].location = route['legs'][i].start_location
}
for (var i = 0; i < waypts.length; i++) {
createMarker(waypts[i].location, i, true);
}
}
var request = {
origin: source,
destination: destination,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: pardas,
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;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
The DirectionsService returns all the information you need to calculate the total time and distance, you don't need to use the DistanceMatrix.
Per this related question: Google Maps API: Total distance with waypoints
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("dvDistance").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
proof of concept fiddle
code snippet:
var source, destination;
var directionsService = new google.maps.DirectionsService();
var stop;
var markers = [];
var waypts = [];
stop = new google.maps.LatLng(6.347033, -75.559017)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(6.348764, -75.562970)
waypts.push({
location: stop,
stopover: true
});
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false,
});
window.onload = function() {
var mapOptions = {
zoom: 15,
//center: new google.maps.LatLng(6.3490548, -75.55802080000001),
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
source = new google.maps.LatLng(6.3490548, -75.55802080000001);
destination = new google.maps.LatLng(6.334624, -75.556157);
var request = {
origin: source,
destination: destination,
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);
}
});
}
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("dvDistance").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#dvMap {
height: 100%;
width: 50%;
margin: 0px;
padding: 0px;
}
#dvPanel {
height: 100%;
width: 50%;
margin: 0px;
padding: 0px;
float: right;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="dvDistance"></div>
<div id="dvPanel"></div>
<div id="dvMap"></div>

Access javascript variable

I'am trying to create a web app with google map direction API,In a variablesummaryPanel.innerHTMLContains the details regarding the address and distance.I required to use distance for other calculations ,so how can i access the variable,can we access the variable from the angular controller?
script.js
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions-panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
'</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
console.log(summaryPanel.innerHTML);//Variable required to access
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
Using jQuery:
var htmlString = $(summaryPanel).html();
Then you'll have to parse whatever htmlString comes out to, but it will have what you're looking for.
Source: http://api.jquery.com/html/

google maps javascript api does not get me any adress

I am using this code ,
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions-panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
'</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
above code works fine.But when I changed the part below,it gives me error code "Directions request failed due to zero_results".because of it can not find this coordinat (36.9165612, 34.895210200000065) in map.But actually I am getting this coordinats another google api.so this coordinat exists.Even it finds the address in google map https://www.google.com.tr/maps/place/36.9165612,+34.895210200000065/data=!4m2!3m1!1s0x0:0x0?sa=X&ved=0ahUKEwiB6OT03JjNAhWLLMAKHZrIApgQ8gEIGjAA
lastly when I change to coordinat to (41.85, -87.65), it works fine coz it finds the address.Many less coordinats works like this.
I want to find all coordinats in google maps.
How can I solve this problem?
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: new google.maps.LatLng(36.9165612, 34.895210200000065),
stopover: true
});
}
}
It may not find an address from a lat and lng. You have to consider it.
More info here and here

Google Maps Javascript API - Results Formatting

I need to display the results of a distance matrix request without geocoding. The problem is my locations are too close together and thus the resultant geocoded addresses are the same.
If I could display the results with the variable names or even the original lat/lon coordinate pairs I would be able to distinguish between the locations.
I checked the documentation for the Distance Matrix Response Elements and I did not see this functionality.
The javascript is below.
function initMap() {
var bounds = new google.maps.LatLngBounds;
var markersArray = [];
var origin1 = {lat: 37.2692332704, lng: -81.7261622975};
var origin2 = {lat: 37.2625193371, lng: -81.7183645359};
var origin3 = {lat: 37.1315998981, lng: -81.8552666961};
var destinationA = {lat: 37.1854557602, lng: -81.7946133276};
var destinationB = {lat: 37.1751720467, lng: -81.792833926};
var destinationC = {lat: 37.1595851233, lng: -81.8570206921};
var destinationIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=O|FFFF00|000000';
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.2692332704, lng: -81.7261622975},
zoom: 8
});
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1, origin2,origin3],
destinations: [destinationA, destinationB,destinationC],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
var showGeocodedAddressOnMap = function(asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(bounds.extend(results[0].geometry.location));
markersArray.push(new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
}));
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
//geocoder.geocode({'address': originList[i]},
//showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
//geocoder.geocode({'address': destinationList[j]},
//showGeocodedAddressOnMap(true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
}
});
}
Thanks in advance.
The results are returned in the order requested.
origin1 - destination1
origin1 - destination2
origin1 - destination3
origin2 - destination1
---
origin3 - destination3
You can use your original request to identify the exact coordinates used to calculate the result.
proof of concept fiddle
code snippet:
function initMap() {
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var destinationIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=O|FFFF00|000000';
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 37.2692332704,
lng: -81.7261622975
},
zoom: 8
});
var originArray = [origin1, origin2, origin3];
var destinationArray = [destinationA, destinationB, destinationC];
for (var i = 0; i < originArray.length; i++) {
var oMarker = new google.maps.Marker({
position: originArray[i],
map: map,
label: "" + i,
icon: originIcon
});
bounds.extend(oMarker.getPosition());
}
for (var i = 0; i < destinationArray.length; i++) {
var dMarker = new google.maps.Marker({
position: destinationArray[i],
map: map,
label: "" + i,
icon: destinationIcon
});
bounds.extend(dMarker.getPosition());
}
map.fitBounds(bounds);
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: originArray,
destinations: destinationArray,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
outputHTML = "";
outputHTML += "<table border='1'><thead><tr><th>Oi</th><th>origin</th><th></th><th>Di</th><th>destination</th><th>distance</th><th>duration</th></tr></thead><tbody>";
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputHTML += "<tr><td>O" + i + "</td><td>" + originArray[i].lat + "," + originArray[i].lng + "</td><td> to </td><td>D" + j + "</td><td>" + destinationArray[j].lat + "," + destinationArray[j].lng +
"</td><td>" + results[j].distance.text + "</td><td> in " +
results[j].duration.text + "</td></tr>";
}
}
outputHTML += "</tbody></table>";
outputDiv.innerHTML = outputHTML;
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
var origin1 = {
lat: 37.2692332704,
lng: -81.7261622975
};
var origin2 = {
lat: 37.2625193371,
lng: -81.7183645359
};
var origin3 = {
lat: 37.1315998981,
lng: -81.8552666961
};
var destinationA = {
lat: 37.1854557602,
lng: -81.7946133276
};
var destinationB = {
lat: 37.1751720467,
lng: -81.792833926
};
var destinationC = {
lat: 37.1595851233,
lng: -81.8570206921
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="output"></div>
<div id="map"></div>

For loop inside waypoints - Google Maps [duplicate]

This question already has an answer here:
Google Directions Service with Waypoints not working
(1 answer)
Closed 8 years ago.
I am trying to display a route with waypoints for a trip. I save all the coordinates to a MySQL varchar attribute and then pull it out with php and slice it up into an array so the two array elements fruits[0] and fruits[1] represent the start, the fruits[2] and fruits[3] represent the first waypoint, that is the second place visited and so on.
I am trying to display the route of the trip and it works perfectly if I don't use waypoints, that is, if I don't populate the waypts array with all points except start and finish.
This is my code
<style>
#map-canvas {
width: 100%;
height: 400px;
}
</style>
<script type="text/javascript">
var fruits = <?php echo json_encode($arr); ?>;
for (var i = 0; i < fruits.length; i+=2) {
//text += cars[i];
}
</script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var dbk = new google.maps.LatLng(fruits[0], fruits[1]);
var mapOptions = {
zoom: 11,
center: dbk,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var waypts = [];
for (var i = 2; i < fruits.length -2; i+=2) {
waypts.push(new google.maps.LatLng(fruits[i], fruits[i+1]));
};
var request = {
origin: new google.maps.LatLng(fruits[0], fruits[1]),
destination: new google.maps.LatLng(fruits[fruits.length-2],fruits[fruits.length-1] ),
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
} else {
alert("directions response "+status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You need to use Directions Waypoints for the waypoints.
var waypts = [];
for (var i = 2; i < fruits.length -2; i+=2) {
waypts.push({
location:new google.maps.LatLng(fruits[i], fruits[i+1]),
stopover:true
});
};
Working example with single LatLng waypoint

Categories

Resources