I need to get the duration_in_traffic for 3 legs of a journey. I make a call to google directions service with an origin, 2 waypoints, and a destination. Google then returns a JSON object with one route, comprised of 3 legs as expected, but only gives duration, not duration_in_traffic. Without the waypoints it does return the duration_in_traffic. If you include the waypoints and set stopover=false, then it routes the journey via the waypoints, reports the duration_in_traffic but doesn't return the information as separate legs.
I need the separate legs as I need to calculate information for each leg (e.g. fuel usage).
I could split the work into 3 separate calls, but that means incurring 3x the cost and paying Google more for the privilege.
Is there a way of getting duration_in_traffic AND having the results split into legs, using just one call?
This really makes sense, after all my investigation, it looks like we have to make 3 different calls to calculate the traffic duration for each routes. I am having the same issue.
But this could help at some point.
https://maps.googleapis.com/maps/api/directions/json?origin=Edison NJ&destination=Morristown, NJ&waypoints=via:Scotch Plains, NJ|via:Basking Ridge, NJ&departure_time=now&key=YOURKEY
You have to use via: keyword in waypoints to plan your destination using specific points. This returns one leg with total duration in traffic and total miles in the route. This should help you.
This describes, when you want to go to Morristown NJ from Edison NJ, you will be going through Scotch Plains and Basking Ridge waypoints.
{
distance: {
text: "19.2 mi",
value: 30859
},
duration: {
text: "40 mins",
value: 2379
},
duration_in_traffic: {
text: "35 mins",
value: 2120
}
For more info go to
https://developers.google.com/maps/documentation/directions/intro#Waypoints
Related
New to HERE, so sorry for basic question.
We need to optimize routes. Typically start and end at some location, 20-30 waypoint along the way. Some of the stops have delivery windows (i.e deliver between 10:00 and 11:00 AM) some do not. Best way to accomplish this? Any relevant samples we can look at? Thanks
One of the option is HERE Matrix Routing API, it provides following features:
Large number of origins and destinations (up to 10,000)
Live traffic and historical speed patterns
Car, Truck, Pedestrian and Bicycle modes
Truck attributes such as dimensions, weight, tunnel restrictions and more
Avoiding areas and routing features, e.g., toll roads, ferries and motorways.
Choice between synchronous and asynchronous APIs for flexible result downloads
API document URI https://developer.here.com/documentation/matrix-routing-api/8.3.0/dev_guide/index.html
Request would be like :
POST https://matrix.router.hereapi.com/v8/matrix?async=false
Content-Type: application/json
Body:
{
"origins": [{"lat": 0.0, "lng": 0.0}, {"lat": 0.1, "lng": 0.1}, ...],
"destinations": [...], // if omitted same as origins
"regionDefinition": {
"type": "circle",
"center": {"lat": 0.0, "lng": 0.0},
"radius": 10000
}
}
Another option is HERE Routing API :
https://route.ls.hereapi.com/routing/7.2/calculateroute.json?waypoint0=52.5160%2C13.3779&waypoint1=52.5206%2C13.3862&mode=fastest%3Bcar%3Btraffic%3Aenabled&departure=now&apiKey=<API_KEY>
With the Tour Planning API you can solve many version of the vehicle routing problem. You can set delivery time windows for your depots and you can even specify details about your vehicles.
Here's an example with time windows.
I use the here PlacesServices to retrieve information what's around me. Often I get results that are quite ambiguous / duplicate because outdated data appears to be in the result set that reduces the quality quite significantly. How can we feed back changes to the community or how and when does here get updates for those categories, e.g. restaurants or petrol-stations?
Is there a way to dedup?
This is a good example for 3/6 duplicates (same petrol station) since the chain changed some time ago dependent of the direction on the highway.
https://places.ls.hereapi.com/places/v1/places/276u1jne-8c62ebd6159c441eba290df4efdcfd1d;context=Zmxvdy1pZD02ZWQ0YzViNS0wMzgxLTUxZDAtOTg2ZC00NjQ3YTVjNWJhYTJfMTU3NTY2NjU1MTYwM18wXzE1NCZyYW5rPTI
https://places.ls.hereapi.com/places/v1/places/276u1jne-3c240a265c6e48d698a400b7d8738202;context=Zmxvdy1pZD02ZWQ0YzViNS0wMzgxLTUxZDAtOTg2ZC00NjQ3YTVjNWJhYTJfMTU3NTY2NjU1MTYwM18wXzE1NCZyYW5rPTQ
3 chains for a single petrol station
Finally, is there a solution how I'd only obtain those in my travel direction?
var query = {"in": lat +"," + lng +";r="+distance*1000,"cat" : categories +",pretty"};
let entryPoint = H.service.PlacesService.EntryPoint;
await this.places.request(entryPoint.EXPLORE, query,
function(response) {
values = response.results.items;
}, function(resp) {
console.log('ERROR: '+resp);
});
Best regards and many thanks in advance
O.
In general the feedback related to HERE Map data can be reported by either the Map Feedback API , the details on the API are available on the documentation page , or The Online Tool HERE Map Creator could be used.
With respect to retrieving POIs, it is possible to request POIs along the route using the "browse/by-corridor" (documentation) end point where the route shape and a radius could be provided as a corridor. It should be noted however the API does not consider the heading direction of the route and may return POIs on the other side of a road. Example :
https://places.ls.hereapi.com/places/v1/browse/by-corridor?route=[52.5199356,13.3866272|52.5100899,13.2816896|52.4351807,13.1935196|52.4107285,13.1964502|52.38871,13.1557798|52.3727798,13.1491003|52.3737488,13.1154604|52.3875198,13.0872202|52.4029388,13.0706196|52.4105797,13.0755529]&apiKey=API_KEY
I have the following script which is being used in a spreadsheet to calculate the driving distance between two cities or a city and a zip code of another city. It is being run for approximately 25 locations simultaneously. To better explain, I have cell B3 in which I enter a new city every time. The script is then used in cells adjacent to my 25 plant locations to calculate the distance from each of my plants to the variable city.
It uses google sheets built in mapping api and works on 80% of the calculations but returns "TypeError: Can Not Read Property "legs" from undefined. (line 16). The plants that it fails on vary with every new city so its not like it is for certain locations. It is almost like the api times out before it completes some of them. I split it into two separate scripts with a varied name and that worked for a day but then 20% fail again.
To make things slightly more odd, I have another script that sorts the plants based on closest distance to the variable address. When you sort the plants, even the ones with errors go to their correct location based on distance. So it is like the distance script is obtaining the correct disance but displaying the error anyways.
Clear as mud? Would love any input I could get on how to correct the issue or an alternate mapping api that could solve my problems.
function distancecalcone(origin,destination) {
var directions = Maps.newDirectionFinder()
//Set the Method of Transporation. The available "modes" are WALKING, DRIVING, BICYCLING, TRANSIT.
.setMode(Maps.DirectionFinder.Mode.DRIVING)
//Set the Orgin
.setOrigin(origin)
//Set the Destination
.setDestination(destination)
//Retrieve the Distance
.getDirections();
return directions.routes[0].legs[0].distance.value/1609.34;
}
Have you tried using a try-catch block around directions.routes[0].legs[0].distance.value ?
try{
return directions.routes[0].legs[0].distance.value/1609.34;
}
catch (e){
console.log("error",e)
}
or you could try something like this
alert(directions);
alert(directions.routes[0]);
alert(directions.routes[0].legs[0]);
alert(directions.routes[0].legs[0].distance);
alert(directions.routes[0].legs[0].distance.value);
and so on...to find out which one comes up as undefined the first. That might help you to debug the issue.
Enable Direction Api
1)Go to "google cloud platform"
2)go to "Api and services"
3)search for "direction api" and enable it
The directions service is subject to a quota and a rate limit. Check the return status before parsing the result.
For lots of distances (or at least more than 10), look at the DistanceMatrix.
I'm able to run the script from the Script editor, but not from spreadsheet. The error is "unable to read property legs" when the function is called from spreadsheet. But the property is in place when called from Script editor and contain correct values.
You probably need to use WEB API and have API KEY:
Google Apps Script - How to get driving distance from Maps for two points in spreadsheet
I am trying to get the travel time with traffic between 2 sets of lat/long coordinates. I can call the Google Distance Matrix API, but I am only getting travel time without traffic. The API notes which I have read say to use a parameter called departure_time. Here is the excerpt:
departure_time specifies the desired time of departure as seconds since midnight, January 1, 1970 UTC. The departure time may be specified by Maps for Business customers for to specify the departure_time to receive trip duration considering current traffic conditions. The departure_time must be set to within a few minutes of the current time.
I found this website to give me that time: epochconverter
However I am still getting the same travel time every time. Here is a sample request, the departure_time parameter would need to be updated (not that it matters).
https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial&departure_time=1408046331&origins=37.407585,-122.145287&destinations=37.482890,-122.150235
15 minutes is always returned.
Using "maps dot google dot com" a travel time of 19 mins is returned when traffic is taken into account.
If anyone can help me get the travel time with traffic from the Distance Matrix API, that would be greatly appreciated.
No need for business license, just need an API key from project on https://console.developers.google.com/ with Google distance Matrix enabled.
For results as on google map use traffic_model with values pessimistic,optimistic and do keep in mind "The departure_time must be set to within a few minutes of the current time" without that it will always return 15 minutes.
That feature appears to only be available to Maps for Business customers, according to the docs.
Even with business licence you can only query departure_time 5 minutes from now if you're using traveling mode is driving
https://developers.google.com/maps/documentation/distancematrix/
According to the google docs "departure_time" can only be used if "mode"(travel mode) is set to "Driving"(which is the default travelMode) and an Api KEY is included in your request.
There is also an optional parameter "trafficModel".
Here is an example url with proper parameters.
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.598566%2C-73.7527626&mode=driving&departure_time=now&traffic_model=optimistic&key=YOUR_API_KEY
To use distance matrix api as javascript code use it as mentioned in this doc.
https://developers.google.com/maps/documentation/javascript/distancematrix
**Imp:**There are many limitations with this API. Most of the features are available only for premium users.Read the above doc carefully.
Please try with below code.
var origin = new google.maps.LatLng(detectedLatitude,detectedLongitude);
var destination = new google.maps.LatLng(latitudeVal,langtitudeVal);
var service = new google.maps.DistanceMatrixService();var date = new Date();
date.setDate(date.getDate() + 1);
var DrivingOptions = {
departureTime: date,
trafficModel: 'pessimistic'
};
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
drivingOptions : DrivingOptions,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true,
avoidHighways: false,
avoidTolls: false
}, response_data);function response_data(responseDis, status) {
if (status !== google.maps.DistanceMatrixStatus.OK || status != "OK"){
console.log('Error:', status);
// OR
alert(status);
}else{
alert(responseDis.rows[0].elements[0].distance.text);
}});
Please refer this document click here
This API can solve your problem - https://distancematrix.ai/dev
It takes into consideration the traffic conditions, road constructions, and other restrictions when calculating travel time. And if you were using Google's API before for you will be easy, because you don't need to rewrite code.
Regarding the departure time, you will find the following in the documentation:
"departure_time — a desired time of the departure. You can specify the time as an integer in seconds since midnight, January 1, 1970, UTC. Alternatively, you can specify a value of now, which sets the departure time to the current time (correct to the nearest second). If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time). The departure_time must be set to the current time or some time in the future. It cannot be in the past. Results for a given request may vary over time due to the changes in the road network, updated average traffic conditions, and the distributed nature of the service. Results may also vary between nearly-equivalent routes at any time or frequency."
Follow these recommendations, and you won't have this problem. Besides, you can easily contact the developers and ask any questions concerning your situation.
Disclaimer: I work at a company that creates this API.
If you are using golang client, set DepartureTime to "now" in the input parameter DirectionsRequest of the Directions func.
Is there any standard format to supply the address string to Google GeoCoding API to get the most accurate results on map.
For Eg. following query not giving correct result.
http://maps.googleapis.com/maps/api/geocode/xml?address=bloom,Bloomfield,CT,06002,USA&sensor=false
Thanks
Mandeep
I believe the suggested format is:
House Number, Street Direction, Street Name, Street Suffix, City, State, Zip, Country
The results get less specific the less information you can supply, obviously.
In your sample, the geocoder is searching for a street named 'bloom', of which there are similar matches in OH instead of CT. Removing 'bloom' from the query and then searching returns Bloomfield, CT.
Definition of Google address search:
address - The street address that you want to geocode, in the format used by the national postal service of the country concerned. Additional address elements such as business names and unit, suite or floor numbers should be avoided.
https://developers.google.com/maps/documentation/geocoding/#geocoding
How should I format my geocoder queries to maximise the number of successful requests?
The geocoder is designed to map street addresses to geographical coordinates. We therefore recommend that you format geocoder requests in accordance with the following guidelines to maximise the likelihood of a successful query:
Specify addresses in accordance with the format used by the national postal service of the country concerned.
Do not specify additional address elements such as business names, unit numbers, floor numbers, or suite numbers that are not included in the address as defined by the postal service of the country concerned.
Use the street number of a premise in preference to the building name where possible.
Use street number addressing in preference to specifying cross streets where possible.
Do not provide 'hints' such as nearby landmarks.
https://developers.google.com/maps/faq#geocoder_queryformat
I found the answer incomplete and it lacked a source.
Look here: https://developers.google.com/places/documentation/autocomplete#place_autocomplete_responses
The maps autocompletion API from google returns a much simpler format: "Street address, City, Country"
Now you can use a string like that to search for an address and it should lead to one exact result.
In addition if you use the autocompletion API you will get a unique identifier too which can be used for further detail requests.
The format of the street address greatly depends on the location where you actually are.
In the US "House number, street direction, street name, street suffix" might make sense, in most of Europe it will not lead to successful query.
Addresses in most of EU are different (often "Streetname number suffix") like "Kumpelstraat 25A","Psolevcu 331/26b") and I guess we'd be surprised if we look at some eastern countries.
So if you bind your code to a single area (US, most of EU) you might be good hardcoding the format.
If you want to have a more flexible system you either need to find out propper formating for your target audience or query one of googles APIs to automatically get a proper string.
The one I linked is very good but requires an API key with a free request limit per day.
I stumbled upon this question and found a solution that worked for me:
I think the answer can be found by using component filtering, look at:
https://developers.google.com/maps/documentation/geocoding/#ComponentFiltering
An example in Javascript:
var request = require('request');
var url = "https://maps.googleapis.com/maps/api/geocode/json?" +
"address=Herengracht 180" +
"&components=postal_code:1016 BR|country:NL" +
"&sensor=false";
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
else {
console.log('error', error);
}
});
No need to avoid apartment units. This works:
https://maps.googleapis.com/maps/api/geocode/xml?address=14202+N+42nd+St+Unit+301+33613
"Apt", "Room", and "Suite" work as well
They all return 301 as subpremise and are shown in "formatted_address" as "#301."
Paul sends...
I found that official country codes like "US", "DE", "FR" do not work well. Replacing them with the full country name gives much better results for me.
I did not find a source where that is stated.