Google Distance Matrix Api: travel time with traffic - google-maps-api-3

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.

Related

How I can filter meetings which are going to start in given time range

I am working on a specific requirement to filter out any meetings that are going to start in next 15 mins of a given calendar.
I can see that there is timeMax query option which will give events starting before given time but the problem I am facing is that I am also getting older events (which are done in past). Any way to get records only froj now to next 15 mins?
I tried query using syncToken but I guess that doesnt works with timeMax so not able to get just the delta and instead getting all the events.
Calendar Event List API
As suggested under the comments, you could be using timeMin and timeMax. It should be something similar to:
timeMin = 2022-12-27T15:30:00+01:00
timeMax = 2022-12-27T15:45:00+01:00
Notes:
Use the query parameters from above and make sure to respect that it must be RFC3339 timestamp.
This might be the only available option or suggestion when utilizing the event.list to filter them by the 15 minutes mark and check their status. It would be a loop process that could potentially hit a quota.
var request = Calendar.events.list({
'calendarId': calendar_id,
"singleEvents" : true,
"orderBy" : "startTime",
"timeMin": startDate.toISOString(),
"timeMax": maxDate.toISOString()
});
Calendar API limitation
If these suggestions or options are not enough or can be considered workarounds due to the limitations, you could always request a feature by going under Issue Tracker.
References
Events: list
Issue Tracker

Google Analytics: segment discrepancy between API and web reporting

I've had an analytics reporting API running for a while now and unfiltered view results from the API match the web reporting. The issue I'm seeing is when adding a segment to the API report request. The web reporting is frequently returning different values than the API for a handful of the segment/view_id combinations. I'm looking for a recommended settings to review here to understand what is causing the discrepancy, as I'm not sure if this is an program code/API issue, web reporting issue or a configuration for segment/view_id issue.
Notes:
When incorrect, it appears that the web reporting numbers for sessions is averaging 10% higher than what the API returns
A single segment is applied to many view_ids we manage and a high percentage (~80%) are showing the discrepancy, the remainder match.
the modified and created dates for this segment are 5 months old per the web interface, meaning there is not a configuration change within the segment causing the discrepancy
we've compared 2018 YTD to eliminate a time lag data update as an issue.
segments appear to be link to our master account level and applied to the accounts we manage.
currently using v4 of the analytics API for .Net (C#)
Current Questions:
Could this be a setting in how a particular segment was created?
Why would some segment/view_ids match and others not?
Is there a account, property or view_id permission/configuration setting to review as it relates to applying segments?
Any help or insights on what to review here would be helpful.
Forgot the code snippet:
var segmentDimension = new Dimension { Name = "ga:segment" };
var DefaultReportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { date, SourceMedium, Campaign, AdContent, Keyword },
Metrics = new List<Metric> { sessions, Users, NewUsers, Bounces, pageViews, SessionDuration, Goal01Completion, Goal02Completion, Goal03Completion, Goal04Completion },
ViewId = v_id,
PageSize = 10000
};
if (!(segmentId == ""))
{
DefaultReportRequest.Dimensions.Add(segmentDimension);
Google.Apis.AnalyticsReporting.v4.Data.Segment segment = new Google.Apis.AnalyticsReporting.v4.Data.Segment() { SegmentId = segmentId };
DefaultReportRequest.Segments = new List<Google.Apis.AnalyticsReporting.v4.Data.Segment> { segment };
};
var getReportsRequest5 = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { DefaultReportRequest }
};
var batchRequest5 = reportingService.Reports.BatchGet(getReportsRequest5);
var response5 = batchRequest5.Execute();
Thanks in advance for your help,
Mike
Update 2:
After reviewing this further the API call is always pulling a single day of data "Yesterday". The web reporting when pulling that single specific day of data matches. If the web reporting pulls a time range of data around those specific dates (ex: +/- 3 days) the numbers no longer match. It seems like sampling could be in play here, but the web reports we are running indicate 100% of sessions in both pulls. I think the question is how to determine which is more accurate a single day or a time range of data. Has anyone investigate this, I've reproduced it on several of our view_ids.
Thanks,
Mike
Update 3 (rseolution):
Turns out the issue was with how the segment was created and being applied to web reporting. The segment was focused at the User level, meaning aggregated values would change based on the time frame selected. The desired state was having the filters apply to a single day, making session focus a better then user as it contained the segment to the session.
Thanks all,
Mike
Without knowing too much about the details of the segments and views, the first thing I'd like to confirm with you is that you're aware of sampling in GA.
Unless they're all 360 accounts, you'll be subjected to sampling depending on the sessions you're returning for 2018 YTD. Note, sampling is based on sessions on the property level, not view level.
Another thing you can do in your code is to check if the sampling of the % of data matches with the web version VIA the response from the API. On the web version, the sampling info is here:https://i.stack.imgur.com/hcPGD.png

Get Firestore Server Timestamp from the client side

I'm building an app that tracks time. It calculates the time by differentiating the seconds like so:
serverTimestamp: FieldValue // {seconds: number, milliseconds: number}.
getSeconds() {
const createdTime = new Date(this.serverTimestamp * 1000).getTime()
const currentTime = new Date().getTime();
return Math.abs((currentTime - createdTime) / 1000);
}
The problem is that Date's values equal to the current client's device clock, while firestore's timestamp equal to the firestore server, which may cause inequivalence between these two dates.
The leads me with two alternatives:
1. Save Date instead of serverTimestamp().
This way, the difference between these two dates will be accurate. Although, they won't represent the real date. Plus, if the user will change his clock on his machine, then the seconds would be changed too.
2. Create an HTTPS function that retrieves the current server timestamp.
This way, the difference between these two dates will be accurate either. Although, it feels like I'm going too far only to get the current timestamp of the server.
I am probably going to stick with alternative number two. But I was hoping if there's a better solution to achieve my goal.
PS - I'm using #angular/fire. So, solutions from this package would be welcomed.
You can also write the current timestamp with a serverTimestamp, then read the time back out of the location it was just written. Then you can make changes or calculations with that value.

how to use TransportAPI to generate a route at a specified time?

I was using TransportAPI to request a public route that took place at a specified date and time.
But it didnt return any route data. How should I set the date and time?
There's two different TransportAPI endpoints which you might be referring to when you say "public route" here. In both cases you can add date and time to the query:
You might mean "bus/route" - bus timetable information about one particular route. You actually have to specify a bus route (operator and line name) and details of particular departure, so for example here is the 185 bus departure at 11:26 today towards Lewisham:
http://transportapi.com/v3/uk/bus/route/LONDONBUS/185/inbound/490012571T/2017-09-22/11:26/timetable.json?app_id=APP_ID&app_key=APP_KEY
...or you might mean "public/journey". A route (or "journey plan") through the public transport system from one location to another. For example here's a journey plan from Vauxhall to Bethnal Green. The response is not just one route, but multiple alternatives
https://transportapi.com/v3/uk/public/journey/from/lonlat:-0.11966,51.48626/to/lonlat:-0.05703,51.52398/at/2017-10-10/10:00.json?
app_id=APP_ID&app_key=APP_KEY
The /at/2017-10-10/10:00 bit specifies your desired departure time, but you can also say /by/2017-10-10/10:00 to specify a desired arrival time, or you can leave it out (then it just plans for departing now)

Errors When Calculating Distance Between Two Addresses

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

Resources