Let's say you have a map to display KmlLayer objects on it, with toggle checkbox for each KmlLayer object, located in a panel.
var Province = new google.maps.LatLng(47.112754, -70.815223);
var map = new google.maps.Map( document.getElementById('map'), {zoom:7,center:Province} );
And you store in KML files a limited number of routes, to optimize the speed of the map.
Direction's requests are made using Google Maps API v3.
And let's say you have a page containing a Google Map in a hidden div, and you make Direction requests through this API.
The array 'waypoints' holds the coordinates of each start and end point of each polyline needed.
var geo_coords = ''; // holds the results
var y; // counter
var delay_per_request = 1000; // default delay in milliseconds between requests
var current_delay = delay_per_request; // current delay between requests
function calcRoute(start,end) {
setTimeout(function(){
var directionsService = new google.maps.DirectionsService();
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
// Error?
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
document.getElementById('error_text').innerHTML += "<br>" + start + "/" + end
+ "("+status+") :: Interval:"+current_delay+"ms";
window.scrollTo(0, document.body.scrollHeight);
if (current_delay < 2600) {
current_delay += 200;
}
if (current_delay >= 1600) {
delay_per_request = 1600;
}
retry++;
if (retry < 20) {
calcRoute(start,end);
} else {
document.getElementById('error_text').innerHTML += "<br>The script stopped running after "+retry+" retries"
+ " sur " + start + "/" + end + "("+status+") :: Interval:"+current_delay+"ms";
}
// Positive result?
} else if (status == google.maps.DirectionsStatus.OK) {
var myRoute = response.routes[0].overview_path;
for (i in myRoute) {
if (myRoute[i] != undefined) {
geo_coords += myRoute[i].lat() + "," + myRoute[i].lng() + "_";
}
}
geo_coords += "!";
document.getElementById('error_text').innerHTML += "<br><font color=\"green\">" + start + "/" + end
+ "("+status+") :: Interval:"+current_delay+"ms</font>";
window.scrollTo(0, document.body.scrollHeight);
current_delay = delay_per_request;
retry = 0;
Next();
}
});
},current_delay);
}
function Next() {
if (y <= waypoints.length) {
destination = "from:" + waypoints[y] + " to:" + waypoints[y + 1];
geo_desc += description[y] + " => " + description[y+1] + "|";
calcRoute(waypoints[y],waypoints[y+1]);
y = y +2;
} else {
document.getElementById("information").setAttribute('value',geo_coords);
document.getElementById("show_debug_text").setAttribute('value',geo_desc);
document.getElementById("error").setAttribute('value',document.getElementById('error_text').innerHTML);
document.forms["kml"].submit();
}
}
Next();
My question is the following:
Has anyone noticed that Google lower the priority of your requests after you made some request in batch?
The more request you do, the bigger is the number of OVER_QUERY_LIMIT response you get, the bigger is the delay between requests before you have a successful result, and the bigger is the number of requests before you have a successful result.
Is there any workaround or any reason?
(I know I should use the Direction API Webservice to make my requests.)
Thank you!
Related
I'm using Google Distance Matrix API to calculate the driving distance + time from one point to another.
I would like to add if..elseif..else statements to the result of the distance search to vary the answers according to how big the distances (e.g. < or > 10 km) are but I'm a newbie to JS and can't seem to figure out where to stick the statements into my code. Any tips?
Here's my code:
$(function(){
function calculateDistance(origin, destination) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
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) {
$('#result').html(err);
} else {
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
$('#result').html("We can't seem to find "
+ origin + ". Are you sure you entered a valid postcode and place?");
} else {
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
var distance_value = distance.value;
var distance_text = distance.text;
var duration_value = duration.value;
var duration_text = duration.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
$('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + duration_text + " to drive.");
}
}
}
$('#distance_form').submit(function(e){
event.preventDefault();
var origin = $('#origin').val();
var destination = $('#destination').val();
var distance_text = calculateDistance(origin, destination);
});
});
One option is to have the conditional logic in your callback function like this:
function callback(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
$('#result').html(err);
return;
}
if (response.rows[0].elements[0].status !== "OK") {
$('#result').html("We can't seem to find " + origin + ". Are you sure you entered a valid postcode and place?");
return;
}
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
var distance_value = distance.value;
var distance_text = distance.text;
var duration_value = duration.value;
var duration_text = duration.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
if (distance_value > 10000) {
$('#result').html('Distance is greater than 10km');
} else {
$('#result').html('Distance is less than 10km');
}
}
The response validation is done at the beginning of the function and if the request does not return the desired status, you return early and stop the execution of the function. Once these validation statements are out of the way, you can extract all the necessary data from the response and then perform your conditional statements based on any of the values you extracted.
In my example, this is what that looks like:
if (distance_value > 10000) {
$('#result').html('Distance is greater than 10km');
} else {
$('#result').html('Distance is less than 10km');
}
I check to see if the distance value is greater than 10000m (10km) and display a different result based on that.
Here is a JSBin with a working example.
I am having difficulty with the way google calls its maps api. I have the following calling initMap
<script defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY_REMOVED&callback=initMap">
</script>
but inside initMap, the following condition if(getPosition() !== false) { never evaluates to true because init map is done before getPosition() has set its object values.
function initMap() {
// set new map, assign default properties
map = new google.maps.Map(document.getElementById('map'), {
center: { lat, lng }, zoom: 14
});
// check if the requested data is usable (lat, lng === numbers) before trying to use it
if(getPosition() !== false) {
map.setCenter( getPosition() ); // set latest position as the map center
addMarker();
console.log("InitMap ran here");
}
}
How can I make it so initMap waits until getPosition() has had a chance to wait for other functions to do their thing? Here is my complete script so it makes more sense.
<script>
console.log(formatTime(Date()));
// https://developers.google.com/maps/documentation/javascript/geolocation
var map; var marker;
var lat = 65.025984; var lng = 25.470794; // default map location in case no position response is available
var res_data; var res_longitude; var res_latitude; var res_speed; var res_time; // res = response (data from the ajax call)
var xhr = new XMLHttpRequest();
function getPosition() {
pos = {
lat: res_latitude,
lng: res_longitude,
};
return ( isNaN(pos.lat) || isNaN(pos.lng) ) ? false : pos; // return pos only if lat and lng values are numbers
}
function initMap() {
// set new map, assign default properties
map = new google.maps.Map(document.getElementById('map'), {
center: { lat, lng }, zoom: 14
});
// check if the requested data is usable (lat, lng === numbers) before trying to use it
if(getPosition() !== false) {
map.setCenter( getPosition() ); // set latest position as the map center
addMarker();
console.log("InitMap ran here");
}
}
// place marker on the map
function addMarker() {
//console.log("Add Marker ran");
//https://developers.google.com/maps/documentation/javascript/markers
if(marker){ marker.setMap(null); } // remove visibility of current marker
marker = new google.maps.Marker({
position: getPosition(),
map: map,
title: formatTime(res_time),
});
marker.setMap(map); // set the marker
}
function getData() {
xhr.addEventListener("load", reqListener);
xhr.open("GET", "http://example.com/data.txt");
xhr.send();
}
function reqListener() {
// res_data = long, lat, accuracy, speed, time
//console.log("reqListener: " + xhr.responseText);
res_data = '[' + xhr.responseText + ']';
res_data = JSON.parse(res_data);
res_latitude = res_data[0]; res_longitude = res_data[1]; res_accuracy = res_data[2]; res_speed = res_data[3]; res_time = res_data[4];
var formatted_time = formatTime(res_time);
document.getElementById('info').innerHTML = '<span class="info">Lat: ' + res_latitude + '</span><span class="info">Long: ' + res_longitude + '</span><span class="info">Accuracy: ' + res_accuracy + '</span><span class="info">Speed: ' + res_speed + '</span><span class="info">' + formatted_time + '</span>';
addMarker();
}
function formatTime(time) {
var t = new Date(time);
var hours, mins, secs;
if(t.getHours() < 10) { hours = "0" + t.getHours(); } else { hours = t.getHours(); }
if(t.getMinutes() < 10) { mins = "0" + t.getMinutes(); } else { mins = t.getMinutes(); }
if(t.getSeconds() < 10) { secs = "0" + t.getSeconds(); } else { secs = t.getSeconds(); }
var hms = hours +':'+ mins +':'+ secs;
return 'Updated: ' + hms;
}
function init() {
getData();
setInterval(getData, 5000);
}
init();
</script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY_REMOVED&callback=initMap">
</script>
Get rid of the callback=initMap from where you load in the Maps API.
Instead make a call to initMap only from where you are then certain everything is loaded. e.g. at the end of reqListener.
function reqListener() {
res_data = '[' + xhr.responseText + ']';
res_data = JSON.parse(res_data);
res_latitude = res_data[0]; res_longitude = res_data[1]; res_accuracy = res_data[2]; res_speed = res_data[3]; res_time = res_data[4];
var formatted_time = formatTime(res_time);
document.getElementById('info').innerHTML = '<span class="info">Lat: ' + res_latitude + '</span><span class="info">Long: ' + res_longitude + '</span><span class="info">Accuracy: ' + res_accuracy + '</span><span class="info">Speed: ' + res_speed + '</span><span class="info">' + formatted_time + '</span>';
initMap();
addMarker();
}
If you're calling reqListener at repeated intervals and don't want to recreate your map, add some logic to the top of initMap like:
if (map !== null) {
return;
}
I'm using the google places JavaScript API to get place details.
I am encountering two issues to do with JavaScript:
The first is extracting user reviews from the place.reviews array
I can get the place.name, place.phone, and place.formatted_address values but I am unable to retrieve the reviews from the place.reviews array.
I found some sample code on the link below to loop through the reviews array but I can't get it to work. I get script errors for example with the keyword forEach.
Google Places JS API Show Reviews
Is there an easy way to retrieve the values from the reviews array?
These are the script declarations at the top of my HTML document:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>
The Second
I am creating a simple search app so I can view what's around me. I would like to add the distance and time from the start location to the venue the user clicks on i.e. 'London Bridge = 1 km, 10 mins'.
I can get the time and distance values using the Google matrix distance API using a callback function but I don't know how then to pass the values to the main part of my code.
I have had a look at some answers on here but I am still confused about how callback functions work:
function createMarkers(results, PlaceSearchStatus) {
var resultcontent = ''; //stores place results to be displayed on map
var resultdiv = document.getElementById('searchresults');
if (PlaceSearchStatus == google.maps.places.PlacesServiceStatus.OK) {
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
//use the Distance Matrix API to get the distance between this venue and start location
/distancematrix#distance_matrix_responses
var DistanceService = new google.maps.DistanceMatrixService();
var origin1 = new google.maps.LatLng(document.getElementById('lat').value, document.getElementById('lng').value);
var destination1 = results[i].geometry.location;
DistanceService.getDistanceMatrix({
origins: [origin1],
destinations: [destination1],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
function callback(response, DistanceMatrixStatus) {
if (DistanceMatrixStatus != google.maps.DistanceMatrixStatus.OK) {
alert('Distance matrix API Error was: ' + DistanceMatrixStatus);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
//getting the distance value gives more accurate results than the text value but not using that
//alert(results[i].distance.value + ", " + results[i].duration.value);
//get the time and distance to this location from our start location
// Need to fix. this isn't working as this is inside a callback function.
var TimeAndDistance = results[i].distance.text + ", " + results[i].duration.text;
}
}
} // end of distance matrix code
//concatonate the accessible search results and add on the time and distance to the place name
resultcontent += '<p> <h2>' + '<div <input id=\"button2\" type=\"button\" class=\"button\" value=\"' + results[i].place_id + '\" onclick=\"GetIndividualPlaceDetails(this);\">' + results[i].name + '</div> </h2>';
Thanks,
Tom
The following code works for accessing the reviews and I'm using another work around for my second question:
len = place.reviews.length;
for (i=0; i<len; ++i) {
resultcontent += place.reviews[i].rating + ' stars';
resultcontent += ', On ' + place.reviews[i].time + ' ' + place.reviews[i].author_name + ' said:';
if (!!place.reviews[i].text) resultcontent += '<br />' + place.reviews[i].text;
}
}
I' m having this problem , when I load my page and insert Origin and Destination, after clicking the button "locate" it doesn't show anything in the google map, because it says Response is not an object , so I tried to stamp it with console.log and it says Response=null , but if I reload the page and click fast on Locate , then it draws the route.
Here's the code
function init(){
var latlng = new google.maps.LatLng(40.635636, 17.942414);
var mapOptions = { zoom: 12, center: latlng };
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function updateMap(){
init();
var originGeocoder = new google.maps.Geocoder();
var destinationGeocoder = new google.maps.Geocoder();
var origin = document.getElementById( "origin" ).value + " Brindisi 72100";
var destination = document.getElementById( "destination" ).value + " Brindisi 72100";
var directionsService2 = new google.maps.DirectionsService();
originGeocoder.geocode( { 'address': origin }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK ) {
var startLatLng = results[0].geometry.location;
var oLat = startLatLng.lat();
var oLng = startLatLng.lng();
document.getElementById('cStart').innerHTML = oLat + " " + oLng;
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Chiamata asincrona alle API per ottenere Lat e Lng dell' indirizzo di destinazione
destinationGeocoder.geocode( { 'address': destination }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK ) {
var destLatLng = results[0].geometry.location;
var dLat = destLatLng.lat();
var dLng = destLatLng.lng();
document.getElementById('cDestination').innerHTML = typeof dLat;
document.getElementById('cDestination').innerHTML = dLat + " " + dLng;
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Salva in req[] le varie distanze tra le paline e la destinazione
singleObjToStop(origin,destination,function(paline,req,reqO){
console.log("1");
//Trova la palina piĆ¹ vicina alla destinazione
calcSingleDis(paline,req,reqO,function(w2,w1){
console.log("2");
//Disegna i waypoints(?)
reqEnd(origin,destination,w1,w2,function(request){
console.log("3");
directionsService2.route(request, function(response, status) {
console.log("4");
console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("distance");
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 + " ";
summaryPanel.innerHTML += route.legs[i].duration.text + "<br /><br />" ;
}
computeTotalDistance(response);
}
else{
console.log("ENTRA QUA STRONZO");
console.log("Fermata partenza = " + w1);
console.log("Fermata arrivo = " + w2);
}
});
directionsDisplay.setMap(map);
});
});
});
}
function singleObjToStop(origin,destination,callback){
var data=<?php echo $data; ?>;
var a,b,i=0;
var paline = new Array();
var req = new Array();
var reqO = new Array();
var num = <?php echo $n; ?>;
$.each(data, function(fieldName, fieldValue) {
a=fieldValue.geoLat;
b=fieldValue.geoLong;
a=parseFloat(a);
b=parseFloat(b);
paline[i]=new google.maps.LatLng(a,b);
req[i] = {
origin:paline[i],
destination:destination,
travelMode: google.maps.TravelMode.WALKING
};
reqO[i] = {
origin:origin,
destination:paline[i],
travelMode: google.maps.TravelMode.WALKING
};
i++;
if(i==num){
callback(paline,req,reqO);
}
});
}
function calcSingleDis(paline, req, reqO, callback) {
var directionsService = new google.maps.DirectionsService();
var c = 10000000;
var w2 = new google.maps.LatLng(0, 0);
var w1 = new google.maps.LatLng(0, 0);
var num = <?php echo $n; ?>;
var j = (num - 1);
var t;
var cO = 10000000;
var numO = <?php echo $n; ?>;
var jO = 0;
for (j = 0; j < num; j++) {
t = 0;
directionsService.route(req[j], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//directionsDisplay.setDirections(response);
var troute = response.routes[0];
var dis = parseFloat((troute.legs[0].distance.text).replace(",", "."));
document.getElementById('test').innerHTML = dis;
//se distanza minore di quella minore trovata fin ora la cambia
if (dis < c) {
w2 = paline[j - num];
c = dis;
}
if (t == (num - 1)) {
console.log("QUA ENTRA LOL");
for (jO = 0; jO < numO; jO++) {
console.log("E NON ENTRA MANNAC");
t = 0;
directionsService.route(reqO[jO], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log("E NON ENTRA MANNAC22222");
//directionsDisplay.setDirections(response);
var troute = response.routes[0];
var disO = parseFloat((troute.legs[0].distance.text).replace(",", "."));
document.getElementById('test').innerHTML = dis;
//se distanza minore di quella minore trovata fin ora la cambia
if (disO < cO) {
w1 = paline[jO - numO];
cO = disO;
}
if (t == (numO - 1)) {
console.log("W1 = " + w1);
console.log(response);
callback(w2, w1);
}
}
jO++;
t++;
});
}
}
}
j++;
t++;
});
}
}
function reqEnd(origin,destination,w1,w2,callback){
var request = {
origin:origin,
destination:destination,
waypoints: [{location: w1} , {location: w2}],
//waypoints: [{location: w2}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
callback(request);
}
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";
}
google.maps.event.addDomListener( window, 'load', init );
The problem is related to the limit of query that you can use with Google Maps API v3.
You can take a look here: https://developers.google.com/maps/documentation/business/faq#google_maps_api_services
You probably do lots of requests to the API with your program, while you have quite restrictive limits as you can see from google Q&A.
Applications should throttle requests to avoid exceeding usage limits,
bearing in mind these apply to each client ID regardless of how many
IP addresses the requests are sent from.
You can throttle requests by putting them through a queue that keeps
track of when are requests sent. With a rate limit or 10 QPS (queries
per second), on sending the 11th request your application should check
the timestamp of the first request and wait until 1 second has passed.
The same should be applied to daily limits.
Even if throttling is implemented correctly applications should watch
out for responses with status code OVER_QUERY_LIMIT. If such response
is received, use the pause-and-retry mechanism explained in the Usage
limits exceeded section above to detect which limit has been exceeded.
You could find useful: How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?
The Google Maps API provides a geocoder class for geocoding and reverse geocoding dynamically from user input. read more check Geolocation demo here and more HTML5 Geolocation to check here
I am trying to have a function for calculating routes for google maps be dynamically changed based on data retrieved from a .getJSON. I have tried including the bulk of the function calcRoute() under a .done function, but I am receiving an error in property waypoints in the javascript console. I am at a loss as what to do, because when I don't include the bulk of the function under the .done, the array remains blank (asynchronous call with the .getJSON. Here is the code to give you a better idea:
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var data = $.getJSON("/westcoast_map.php", {
westcoast_id: $('.opener').data('westcoast_id')
}, function(json) {
return json[1];
});
data.done(function(theData) {
waypts = theData[1];
console.log(waypts); //this spits out the array in the proper format, i.e. {location:city, state, stopover:true},...etc...
var request = {
origin: start,
destination: end,
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>';
}
}
});
});
}
i'm still not sure what you problem is, because the code pared you show, should at least work from the logical part. but there are parts where it is not clear what you try to achive:
var data = $.getJSON("/westcoast_map.php", {
westcoast_id: $('.opener').data('westcoast_id')
}, function(json) {
return json[1];
});
if you expect here that data will become json[1], then your assumption is wrong.
$.getJSON returns always jQuery XHR. the callback function will be called later when the browser received the data.
Here a little example to understand how async works:
the callback functions 1 and 2 are called when the client gets the response for the request, but not before the original script was completely executed, so doSomethingElse() will be always called before the callback function 1 and 2 are executed.
the order in which callback function 1 and 2 are executed depends on which response arrives first.
var test = [];
preparesSomeStuff();
$.getJSON("someurl1",{},function() {
//Callback Function 1
});
doSomething();
$.getJSON("someurl2",{},function() {
//Callback Function 2
});
doSomethingElse();
//<<END OF SCRIPT>>
if you don't want to have your whole code inside of the callback function (e.g. because of readability) you could do it the following way:
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
$.getJSON("/westcoast_map.php", {
westcoast_id: $('.opener').data('westcoast_id')
}, function(theData) {
calcualteRoute(theData[1], start, end);
});
//if you place code here it will be executed before displayResult will be called because getJSON is async
}
function calcualteRoute(waypts, start, end) {
console.log(waypts); //this spits out the array in the proper format, i.e. {location:city, state, stopover:true},...etc...
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
displayResult(response,status);
}
});
//if you place some code here it will be executed BEFORE displayResult will be called, because
//directionsService.route is async
}
function displayResult(response, status) {
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>';
}
}