shortest route when using waypoints - javascript

i can use waypoints perfectyl.but i can not get shortest directions.i try to use route alternatives but it doesn't work. i need some thing like this : http://i58.tinypic.com/2vjbt6d.jpg
is there any way ?
my codes
function codeAddress(adres) {
var address = adres;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
}
function calcRoute() {
var grid = document.getElementById('GridView1');
var start = document.getElementById('DropDownList_ilce').value + "," + document.getElementById('DropDownList_il').value;
var end = document.getElementById('GridView1').rows[grid.rows.length - 1].cells[4].innerHTML + "," + document.getElementById('GridView1').rows[grid.rows.length - 1].cells[3].innerHTML;
var waypts = [];
for (var i = 0; i < grid.rows.length - 2; i++) {
waypts.push({
location: document.getElementById('GridView1').rows[i+1].cells[4].innerHTML + "," + document.getElementById('GridView1').rows[i+1].cells[3].innerHTML,
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);
}
});

As I said in my comment, the API seems to give no option parameter to return the shortest route by default.
The key here is to use provideRouteAlternatives: true as DirectionsRequest property:
var request = {
origin: 'cerkeş,çankırı',
destination: 'diyarbakır',
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: true
};
For the given origin and destination, this will return 2 separate routes. One of 970km and one of 1137 km.
Then you will have to calculate which route is the shortest. You could do something like that:
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var distance = null;
var routeIndex = 0;
// Loop through the routes to find the shortest one
for (var i=0; i<response['routes'].length; i++) {
var routeDistance = response['routes'][i].legs[0].distance.value;
if (distance === null) {
distance = routeDistance;
routeIndex = i;
}
if (routeDistance < distance) {
distance = routeDistance;
routeIndex = i;
}
}
directionsDisplay.setDirections(response);
// Set route index
directionsDisplay.setOptions({
routeIndex: routeIndex
});
}
});
Note that when you have multiple routes, the key is to set the route index of the one you want to show.
// Set route index
directionsDisplay.setOptions({
routeIndex: routeIndex
});
This example doesn't use waypoints. I believe that if you use waypoints, you will end up with multiple DirectionsLeg legs. In which case, you will have to do a bit more calculation to add each leg distance to find the total route distance.
Hope this helps!

Related

I have created routes in map, but when click on any route infowindow not showing

i have draw routes from Point A to Point B. I am not able to show route information on routes same as appears in google-map.
i need to make it look alike as google map.
and when user click on any route, same route should show selected.
Following are the code.
function calculateRoutes(pierLocation, destinationLocation) {
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: "DRIVING",
provideRouteAlternatives: true,
unitSystem: google.maps.UnitSystem.IMPERIAL,
};
directionsService.route(request, function (result, status) {
if (status === "OK") {
directionsDisplay.setDirections(result);
var summaryPanel = document.getElementById("directions-panel");
summaryPanel.innerHTML = "";
for (var x = 0; x < result.routes.length; x++) {
new google.maps.DirectionsRenderer({
map: map,
directions: result,
routeIndex: x,
});
summaryPanel.innerHTML += "<hr><br><b> Route " + (x + 1) + ":<br>";
var route = result.routes[x];
for (var y = 0; y < route.legs.length; y++) {
var routeSegment = y + 1;
}
}
} else {
window.alert("Directions request failed due to " + status);
}
});
}

Vuejs variable using in function google maps matrix api problem

Vuejs variable using in function google maps matrix api problem.
I am using Google distance matrix api to get the distance between two locations. I declared a variable globally. Changed this variable in function. But as per normal circumstances I should be able to access this changed value of variable after calling my function. But now I am not being able to access the changed value of variable
using : Matrix google maps api + autocomplete input place api
export default {
data () {
return {
data:{
adrdep:{adrs:'',lat:0,lng:0},
adrarr:{adrs:'',lat:0,lng:0},
distance:0,
date:null,
time:null,
check:false,
camion:'',
etage:9,
assenseur:'assenseur'
}
}
},
methods: {
getAddressDatadep: function (addressData, placeResultData, id) {
this.data.adrdep.lat =addressData.latitude;
this.data.adrdep.lng = addressData.longitude;
},
getAddressDataArr: function (addressData, placeResultData, id) {
this.data.adrarr.lat = addressData.latitude;
this.data.adrarr.lng = addressData.longitude;
},
async getDistance(){
var a1={lat:this.data.adrdep.lat,lng:this.data.adrdep.lng};
var a2={lat:this.data.adrarr.lat,lng:this.data.adrarr.lng};
var p1 = new google.maps.LatLng(a1.lat, a1.lng);
var p2 = new google.maps.LatLng(a2.lat, a2.lng);
var origins = [a1.lat + "," + a1.lng];
var destinations = [a2.lat + "," + a2.lng];
var distanceMatrix = new google.maps.DistanceMatrixService();
var distanceRequest = {
origins: origins,
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
};
distanceMatrix.getDistanceMatrix(distanceRequest, function(response, status) {
var totalDistance
if (status != google.maps.DistanceMatrixStatus.OK) {
console.log("error")
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
//debugger;
if (response.rows[0].elements[0].distance != null) {
totalDistance = response.rows[0].elements[0].distance.value;
var totalTime = response.rows[0].elements[0].duration.value;
var ratioPerOneMeter = totalDistance / totalTime;
var PRDifference = 0;
this.data.distance=totalDistance*0.001;
console.log("return distance")
} else {
console.log('The Distance And Time Cannot Be Calculated')
}
}
return totalDistance*0.001;
});
}
};
plz help me :)
calculateDistances() {
var a1={lat:this.data.adrdep.lat,lng:this.data.adrdep.lng};
var a2={lat:this.data.adrarr.lat,lng:this.data.adrarr.lng};
var p1 = new google.maps.LatLng(a1.lat, a1.lng);
var p2 = new google.maps.LatLng(a2.lat, a2.lng);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [p1],
destinations: [p2],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, this.callback);
},
callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var totalDistance = response.rows[0].elements[0].distance.value;
var totalTime = response.rows[0].elements[0].duration.value;
this.data.distance=parseFloat(totalDistance*0.001).toFixed(2);
this.e1=2;
}
}

Will there be any inconsistency with the value calculated?

I have a javascript code like below to calculate the total distance between n markers.
var distance = 0;
function updateTimeAndDistance(timeAndPath) {
realtracPath = timeAndPath.path;
getDistance();
console.log("calculated distance : " + distance);
}
function getDistance() {
for ( var i = 0; i < realtracPath.length - 1 ; i++) {
var startPos = new google.maps.LatLng(realtracPath[i].lat, realtracPath[i].lng);
var endPos = new google.maps.LatLng(realtracPath[i+1].lat, realtracPath[i+1].lng);
var request = {
origin : startPos,
destination : endPos,
travelMode : google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
distance += response.routes[0].legs[0].distance.value;
}
});
}
}
but I am worried that, will there be any inconsistency in the value of the distance calculated as the distance is calculated asynchronously.
EDIT: every time I run this, I am getting distance as zero. I am not understanding why, though I have used the global distance variable.
Thanks.
Try introducing an async callback function like so;
var distance = 0;
function updateTimeAndDistance(timeAndPath) {
realtracPath = timeAndPath.path;
getDistance(function(){
console.log("calculated distance : " + distance);
});
}
function getDistance(cb) {
var latch = realtrackPath.length;
for ( var i = 0; i < realtracPath.length - 1 ; i++) {
var startPos = new google.maps.LatLng(realtracPath[i].lat, realtracPath[i].lng);
var endPos = new google.maps.LatLng(realtracPath[i+1].lat, realtracPath[i+1].lng);
var request = {
origin : startPos,
destination : endPos,
travelMode : google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
distance += response.routes[0].legs[0].distance.value;
latch--
if (latch==0){
cb()
}
}
});
}
}
Note: If the status does not come back as OK nothing will happen. It can be quite handy to have callbacks with function signatures that pass booleans indicating errors etc.

Storing directionsService.route response in object array, and display in another method

I have various origins/destinations, and am looping through all of them to calculate each distance. Pushing each to an array of the following object
routes {
distance: xx,
response:response
}
After all the routes have been added I calculate which has the smallest distance, and map that response. However I am outside the directionService now.. is there a way to map stored responses without calling directionService?
Thanks!!
var routes = [];
function route() {
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
calcRoute(request);
//Here I'd like to display, say routes[0].response.
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
// For each route, display summary information.
var distance = 0;
for (var i = 0; i < route.legs.length; i++) {
distance = distance + route.legs[i].distance.text;
};
//push to routes
routes.push({response:response,distance:distance});
}
});
}

not able to access global variable while using google maps api js

In the below code, I am not able to access the value of variable distances . I think that is because of asynchronous call directionsService.route. How can I get the value variable distances ?
var totalDistance;
var distances = new Array();
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = "ABC XYZ";
var end ;
var points = new Array("Location ABC", "Location PQR", "Location XYZ", "Location more", "And Some other location");
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
center: new google.maps.LatLng(13.0604220, 80.2495830),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor: "crosshair"
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
for(var j=0;j<points.length;j++)
{
end = points[j];
var waypoints = new Array();
for(var i=0; i<points.length;i++)
{
if(i!=j)
{
waypoints.push({location:points[i], stopover: true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypoints,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
totalDistance = 0;
for ( var i=0;i<route.legs.length;i++)
{
totalDistance+=route.legs[i].distance.value;
}
distances.push(totalDistance);
}
});
}
/*Now I want my distances value to be accessed from here i.e outside for loop.*/
/*So that I can compare all the distances obtained */
}
google.maps.event.addDomListener(window, 'load', initialize);
Edit: I have updated complete code.
What I am trying to do : I have fixed start point and some waypoints (order not fixed), I am trying to optimize waypoints, my end point is not fixed, it can be any so that to optimize the path, but it is necessary to provide end point while calling directionsService.route method , so I am taking one of the waypoints as end point and keeping rest other in waypoints only and then calculating total distance of the route. So each of the waypoint will become end point one by one , and others will remain waypoint. I will calculate total distance of all the combinations and then I will show only the directions of the route which has minimum distance.
I would avoid calling asynchronous functions from inside a loop. It can be a pain keeping track of everything.
From what I understand of the question you are trying to find the shortest route with an arbitrary number of destinations. Instead of looping through each waypoint, pass the starting address and all of the destinations to the DistanceMatrix service which returns all of the route lengths from the origin to each waypoint. When the results return sort from shortest to longest. The longest destination will be the end address. Then pass the start address, end address, and remaining waypoints to the DirectionService with the optimizeWaypoints turned on.
Demo: http://jsfiddle.net/bryan_weaver/snYJ2/
Relavent Code:
var map;
var origin = "4100 Ashby Road, St. Ann, MO 63074"
var destinations = [
"2033 Dorsett Village, Maryland Heights, MO 63043",
"1208 Tamm Avenue, St. Louis, MO 63139",
"1964 S Old Highway 94 St Charles, MO 63303"];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin], //array of origins
destinations: destinations, //array of destinations
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
//we only have one origin so there should only be one row
var routes = response.rows[0];
var sortable = [];
var resultText = "Origin: <b>" + origin + "</b><br/>";
resultText += "Possible Routes: <br/>";
for (var i = routes.elements.length - 1; i >= 0; i--) {
var rteLength = routes.elements[i].duration.value;
resultText += "Route: <b>" + destinations[i] + "</b>, "
+ "Route Length: <b>" + rteLength + "</b><br/>";
sortable.push([destinations[i], rteLength]);
}
//sort the result lengths from shortest to longest.
sortable.sort(function (a, b) {
return a[1] - b[1];
});
//build the waypoints.
var waypoints = [];
for (j = 0; j < sortable.length - 1; j++) {
console.log(sortable[j][0]);
waypoints.push({
location: sortable[j][0],
stopover: true
});
}
//start address == origin
var start = origin;
//end address is the furthest desitnation from the origin.
var end = sortable[sortable.length - 1][0];
//calculate the route with the waypoints
calculateRoute(start, end, waypoints);
//log the routes and duration.
$('#results').html(resultText);
}
}
//Calculate the route of the shortest distance we found.
function calculateRoute(start, end, waypoints) {
var request = {
origin: start,
destination: end,
waypoints: waypoints,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var centerPosition = new google.maps.LatLng(38.713107, -90.42984);
var options = {
zoom: 12,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map')[0], options);
geocoder = new google.maps.Geocoder();
directionsDisplay.setMap(map);
calculateDistances();
}
google.maps.event.addDomListener(window, 'load', initialize);
The request is asynchronous.
You have got to wait until the request completes before you check your global variable.
See this answer
Is there any way to wait until the DirectionsService returns results?
EDIT
If you really in a fix you can try making a Synchronous call with
jQuery.ajaxSetup({async:false});
making sure you turn it on again after the method completes
jQuery.ajaxSetup({async:true});
This comes with huge warning however as it can cause your browser to lock up use with
caution
Your alert is firing before the callback has been fired. I'd suggest you create another function and call that from your directionsService.route success callback e.g
var totalDistance; /*Global Variable */
var distances = new Array();
var directionsService = new google.maps.DirectionsService();
/* Some request */
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
totalDistance = 0;
for ( var i=0;i<route.legs.length;i++)
{
totalDistance+=route.legs[i].distance.value;
}
distances.push(totalDistance);
}
afterComplete();// New function call moved outside for loop
});
function afterComplete(){
alert(distances); //Will display null
}
You could then also remove the global variable and actually pass it into the afterComplete function, thus eliminating the need for a global (unless of course it is needed elsewhere)
The DirectionsService is asynchronous. You need to use the results inside the call back function:
function calcRoute() {
for(var j=0;j<points.length;j++)
{
end = points[j];
var waypoints = new Array();
for(var i=0; i<points.length;i++)
{
if(i!=j)
{
waypoints.push({location:points[i], stopover: true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypoints,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
totalDistance = 0;
for ( var i=0;i<route.legs.length;i++)
{
totalDistance+=route.legs[i].distance.value;
}
distances.push(totalDistance);
}
else { alert("Distance Service request not successful:"+status); }
if (distances.length == points.length){
alert(distances);
}
});
}
The global variable will be available after the data comes back from the server and the callback function finishes running. If you need to do something with it once it is available, do that in the call back function.
example

Categories