Difference between duration and duration_in_traffic in Google Directions API Response - google-maps

After working with the Google Directions API for a project I found multiple responses with a (much) shorter value in duration_in_traffic than duration. An example extract from one of the responses i got:
"duration": {
"text": "23 mins",
"value": 1374
},
"duration_in_traffic": {
"text": "16 mins",
"value": 941
},
"end_address": "2868 Mission St, San Francisco, CA 94110, USA",
"end_location": {
"lat": 37.7522994,
"lng": -122.4184684
},
"start_address": "O'Farrell St & Powell St, San Francisco, CA 94102, USA",
"start_location": {
"lat": 37.78640559999999,
"lng": -122.4082846
},
This doesn’t seem to make much sense to me, since i assumed duration is simply the duration without traffic, while duration_in_traffic obviously incorporates traffic conditions. I found an answer on a different thread, but the person answering provided no source to back up his or her claim/observation. Is there more information about the duration response field out there besides the documentation itself, which just describes it as “[indicating] the total duration of this leg”? Is there a source stating that it actually is the average time for that route? And what is the difference between duration and duration_in_traffic?

After searching for more information about the difference between these two fields I came across this thread on the google issue tracker. There it is explained that the value in duration "takes into consideration historical data [...]", while duration_in_traffic "takes into account live traffic data in relation to your departure time". While this doesn't fully explain how the duration value is calculated, it at least extends the official documentation and confirms that historical data is used for the duration value. This also seems to be the only reliable information about the duration field on the web besides the official documentation which isn't very in depth.

Related

Unable to get correct ETA using Google Maps API

I am collecting ETA for few locations for some project work. I get different time duration during different point of time, but there is one case which returns same results
Origin: Acres Club, 411-B, Hemu Kalani Marg, Sindhi Society, Chembur, Mumbai, Maharashtra
Destination: Chhatrapati Shivaji Terminus, Chhatrapati Shivaji Terminus Area, Mumbai, Maharashtra
This always returns 1702 seconds.
Below is the API call I am making:
https://maps.googleapis.com/maps/api/distancematrix/json?origins=Acres%20Club,%20411-B,%20Hemu%20Kalani%20Marg,%20Sindhi%20Society,%20Chembur,%20Mumbai,%20Maharashtra&destinations=Chhatrapati%20Shivaji%20Terminus,%20Chhatrapati%20Shivaji%20Terminus%20Area,%20Mumbai,%20Maharashtra&key=
Let me know if I am missing anything. Thanks in Aadvance.
If I understand correctly you are interested in getting a duration taking into account current traffic conditions. Please note that duration with traffic conditions requires a departure time to be specified in your request.
Have a look at the documentation that reads:
departure_time — The desired time of 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).
For requests where the travel mode is driving: You can specify the departure_time to receive a route and trip duration (response field: duration_in_traffic) that take traffic conditions into account. This option is only available if the request contains a valid API key, or a valid Google Maps APIs Premium Plan client ID and signature. The departure_time must be set to the current time or some time in the future. It cannot be in the past.
https://developers.google.com/maps/documentation/distance-matrix/intro#DistanceMatrixRequests
I would suggest changing you request to
https://maps.googleapis.com/maps/api/distancematrix/json?origins=Acres%20Club%2C%20411-B%2C%20Hemu%20Kalani%20Marg%2C%20Sindhi%20Society%2C%20Chembur%2C%20Mumbai%2C%20Maharashtra&destinations=Chhatrapati%20Shivaji%20Terminus%2C%20Chhatrapati%20Shivaji%20Terminus%20Area%2C%20Mumbai&departure_time=now&traffic_model=best_guess&key=YOUR_API_KEY
In this case you will see something similar to
"rows":[
{
"elements":[
{
"distance":{
"text":"16.2 km",
"value":16206
},
"duration":{
"text":"28 mins",
"value":1702
},
"duration_in_traffic":{
"text":"45 mins",
"value":2715
},
"status":"OK"
}
]
}
],
in your response. Where duration_in_traffic shows duration taking into account current traffic conditions and duration is a typical average duration.
Hope this helps!

What is the standard for formatting currency values in JSON?

Bearing in mind various quirks of the data types, and localization, what is the best way for a web service to communicate monetary values to and from applications? Is there a standard somewhere?
My first thought was to simply use the number type. For example
"amount": 1234.56
I have seen many arguments about issues with a lack of precision and rounding errors when using floating point data types for monetary calculations--however, we are just transmitting the value, not calculating, so that shouldn't matter.
EventBrite's JSON currency specifications specify something like this:
{
"currency": "USD",
"value": 432,
"display": "$4.32"
}
Bravo for avoiding floating point values, but now we run into another issue: what's the largest number we can hold?
One comment (I don’t know if it’s true, but seems reasonable) claims that, since number implementations vary in JSON, the best you can expect is a 32-bit signed integer. The largest value a 32-bit signed integer can hold is 2147483647. If we represent values in the minor unit, that’s $21,474,836.47. $21 million seems like a huge number, but it’s not inconceivable that some application may need to work with a value larger than that. The problem gets worse with currencies where 1,000 of the minor unit make a major unit, or where the currency is worth less than the US dollar. For example, a Tunisian Dinar is divided into 1,000 milim. 2147483647 milim, or 2147483.647 TND is $1,124,492.04. It's even more likely values over $1 million may be worked with in some cases. Another example: the subunits of the Vietnamese dong have been rendered useless by inflation, so let’s just use major units. 2147483647 VND is $98,526.55. I’m sure many use cases (bank balances, real estate values, etc.) are substantially higher than that. (EventBrite probably doesn’t have to worry about ticket prices being that high, though!)
If we avoid that problem by communicating the value as a string, how should the string be formatted? Different countries/locales have drastically different formats—different currency symbols, whether the symbol occurs before or after the amount, whether or not there is a space between the symbol and amount, if a comma or period is used to separate the decimal, if commas are used as a thousands separator, parentheses or a minus sign to indicate negative values, and possibly more that I’m not aware of.
Should the app know what locale/currency it's working with, communicate values like
"amount": "1234.56"
back and forth, and trust the app to correctly format the amount? (Also: should the decimal value be avoided, and the value specified in terms of the smallest monetary unit? Or should the major and minor unit be listed in different properties?)
Or should the server provide the raw value and the formatted value?
"amount": "1234.56"
"displayAmount": "$1,234.56"
Or should the server provide the raw value and the currency code, and let the app format it?
"amount": "1234.56"
"currencyCode": "USD"
I assume whichever method is used should be used in both directions, transmitting to and from the server.
I have been unable to find the standard--do you have an answer, or can point me to a resource that defines this? It seems like a common issue.
I don't know if it's the best solution, but what I'm trying now is to just pass values as strings unformatted except for a decimal point, like so:
"amount": "1234.56"
The app could easily parse that (and convert it to double, BigDecimal, int, or whatever method the app developer feels best for floating-point arithmetic). The app would be responsible for formatting the value for display according to locale and currency.
This format could accommodate other currency values, whether highly inflated large numbers, numbers with three digits after the decimal point, numbers with no fractional values at all, etc.
Of course, this would assume the app already knows the locale and currency used (from another call, an app setting, or local device values). If those need to be specified per call, another option would be:
"amount": "1234.56",
"currency": "USD",
"locale": "en_US"
I'm tempted to roll these into one JSON object, but a JSON feed may have multiple amounts for different purposes, and then would only need to specify currency settings once. Of course, if it could vary for each amount listed, then it would be best to encapsulate them together, like so:
{
"amount": "1234.56",
"currency": "USD",
"locale": "en_US"
}
Another debatable approach is for the server to provide the raw amount and the formatted amount. (If so, I would suggest encapsulating it as an object, instead of having multiple properties in a feed that all define the same concept):
{
"displayAmount":"$1,234.56",
"calculationAmount":"1234.56"
}
Here, more of the work is offloaded to the server. It also ensures consistency across different platforms and apps in how the numbers are displayed, while still providing an easily parseable value for conditional testing and the like.
However, it does leave a problem--what if the app needs to perform calculations and then show the results to the user? It will still need to format the number for display. Might as well go with the first example at the top of this answer and give the app control over the formatting.
Those are my thoughts, at least. I've been unable to find any solid best practices or research in this area, so I welcome better solutions or potential pitfalls I haven't pointed out.
AFAIK, there is no "currency" standard in JSON - it is a standard based on rudimentary types. Things you might want to consider is that some currencies do not have a decimal part (Guinean Franc, Indonesian Rupiah) and some can be divided into thousandths (Bahraini Dinar)- hence you don't want to assume two decimal places. For Iranian Real $2million is not going to get you far so I would expect you need to deal with doubles not integers. If you are looking for a general international model then you will need a currency code as countries with hyperinflation often change currencies every year of two to divide the value by 1,000,000 (or 100 mill). Historically Brazil and Iran have both done this, I think.
If you need a reference for currency codes (and a bit of other good information) then take a look here: https://gist.github.com/Fluidbyte/2973986
Amount of money should be represented as string.
The idea of using string is that any client that consumes the json should parse it into decimal type such as BigDecimal to avoid floating point imprecision.
However it would only be meaningful if any part of the system avoids floating point too. Even if the backend is only passing data and not doing any calculation, using floating point would eventually result in what you see (in the program) is not what you get (on the json).
And assuming that the source is a database, it is important to have the data stored with right type. If the data is already stored as floating point then any subsequent conversion or casting would be meaningless as it would technically be passing imprecision around.
ON Dev Portal - API Guidelines - Currencies you may find interesting suggestions :
"price" : {
"amount": 40,
"currency": "EUR"
}
It's a bit harder to produce & format than just a string, but I feel this is the cleanest and meaningful way to achieve it :
uncouple amount and currency
use number JSON type
Here the JSON format suggested:
https://pattern.yaas.io/v2/schema-monetary-amount.json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"title": "Monetary Amount",
"description":"Schema defining monetary amount in given currency.",
"properties": {
"amount": {
"type": "number",
"description": "The amount in the specified currency"
},
"currency": {
"type": "string",
"pattern": "^[a-zA-Z]{3}$",
"description": "ISO 4217 currency code, e.g.: USD, EUR, CHF"
}
},
"required": [
"amount",
"currency"
]
}
Another questions related to currency format pointed out right or wrongly, that the practice is much more like a string with base units :
{
"price": "40.0"
}
There probably isn't any official standard. We are using the following structure for our products:
"amount": {
"currency": "EUR",
"scale": 2,
"value": 875
}
The example above represents amount €8.75.
Currency is defined as string (and values should correspond to ISO4217), scale and value are integers. The meaning of "scale" is obvious. This structure solves many of the problems with currencies not having fractions, having non-standard fractions etc.

Searching for "nearby" results

I have a dataset, currently just stored in a JSON file, which contains about 40k different geolocations. It looks something like this:
[
{"title": "Place 1", "loc": {"x": "00.000", "y": "00.00000"}},
{"title": "Place 2", "loc": {"x": "00.000", "y": "00.00000"}},
]
where a place's loc is just its coordinates.
I'd like to be able to run queries on this data so, for any given user-inputted loc I can get the n nearest Places.
Or in other words I'd like to write some function f so that this works:
def f(loc, n): ...
f({"x": "5", "y": "5"}, 3) #=> [{"title": "Place 1", "distance": 7.073}, {"title": "Place 2": "distance": 7.073}, {"title": "Place 3", "distance": 7.073}]
if there is a place 1, 2 and 3 all at {x: 0, y: 0}.
I have no idea what the standard way of solving an issue like this is. Using an SQL DB with an index on precomputed distances doesn't work, because the supplied loc is arbitrary. Running through the entire database and calculating distances for everything is far too inefficient, and far too slow. (I need < 30ms response times.)
The only solution that makes sense would be to somehow make "buckets" of close locations (within some r of eachother), and then to computer the distance between the user-given loc and the bucket's loc to narrow down the options first. But I feel like creating such a solution myself would be similar to not using databases at all; there must be a more efficient/industry standard approach. Is there one?
This is a generalized form of the nearest neighbor problem (more formally known as k-nearest neighbor). You're right, the solution that makes sense uses buckets. You could store the buckets in the database which allows you to leverage SQL, just filter out all points not in the appropriate buckets. Depending on your database, this actually may already be implemented for you, which would be the "industry standard" approach you suggested.
Otherwise, writing it yourself is pretty efficient and can be done without deviating too much from the database.
Oracle provides Spatial data capabilities. It has an inbuilt nearest neighbour function SDO_NN which will do the job for you. Only overheard will be putting all the data in db, rest will be taken care of by oracle db.
You can use a database with a point data type and a spatial index like MySQL. You can also use a quadkey or a quadtree. It's subdivide the plane and reduce the dimension. You can download my PHP class Hilbert-curve# phpclasses.org. It's uses a quadkey and can help to organize locations in buckets and build a proximity searching. A quadkey can reduce overlapping searches because of a special database.

Check if city is lies on route obtained from Google Directions API API

I need to check if a particular city will be passed by when going through road obtained from Google Directions API.
I have made an assumption that passing through some cities will require you to take toll roads. I'm making an online service that calculates driving cost based on distance and toll road costs.
For ferries Google API is giving start-end cities. Based on these city names i can detect which ferry will be taken and add costs to the whole driving cost.
There's a problem when taking in example a paid bridge.
Example:
https://maps.google.com/maps?saddr=Londyn,+Wielka+Brytania&daddr=Slagelse,+Dania&hl=pl&ll=55.27364,11.125031&spn=0.621154,1.473541&sll=49.21042,-34.892578&sspn=45.846455,94.306641&geocode=Fa7_EQMd8Cv-_yl13iGvC6DYRzGZKtXdWjqWUg%3BFaxkTQMdeUStACm3zdTgYmFNRjEAD68T8wkEvw&oq=Lond&t=h&mra=ls&z=10
Road from Slagelse, Denmark to London, goes through a paid bridge between Korsor and Nyborg (about 70GBP toll), however in directions this road chunk is defined as:
[7]=>
object(stdClass)#640 (7) {
["distance"]=>
object(stdClass)#641 (2) {
["text"]=>
string(6) "128 km"
["value"]=>
int(127914)
}
["duration"]=>
object(stdClass)#642 (2) {
["text"]=>
string(14) "1 hour 11 mins"
["value"]=>
int(4257)
}
["end_location"]=>
object(stdClass)#643 (2) {
["lat"]=>
float(55.545784)
["lng"]=>
float(9.524455)
}
["html_instructions"]=>
string(115) "Turn <b>right</b> to merge onto <b>E20</b> toward <b>Odense</b><div style="font-size:0.9em">Partial toll road</div>"
How could i check if either Korsor or Nyborg is on the road?
Or should i just assume that paid E20 road always contains that bridge?

Do business pages have user ID numbers?

I created a business page only and am the administrator. Everything that I have read telling me how to find my user id# leads me to the page number. Do business pages have user id#s? If so how do I find it? I need it for the fb:admins content. Please, I have been trying to figure this out for days and my head is physically spinning.
To find the PAGE id, just do the following. http://graph.facebook.com/YourPageNameHere. If you don't have a page name yet (less than X number of fans), then user the # in the link to your page instead of the page name.
example for Coca Cola corp: http://graph.facebook.com/CocaCola
{
"id": "40796308305",
"name": "Coca-Cola",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/276879_40796308305_1578420141_s.jpg",
"link": "https://www.facebook.com/coca-cola",
"likes": 36645415,
"category": "Food/beverages",
"website": "http://www.coca-cola.com",
"username": "coca-cola",
"founded": "1886",
"description": "On May 8, 2011, Coca-Cola marked its 125th anniversary. Created in 1886 in Atlanta, Georgia, by Dr. John S. Pemberton, Coca-Cola was first offered as a fountain beverage at Jacob's Pharmacy by mixing Coca-Cola syrup with carbonated water. \n\nCoca-Cola was patented in 1887, registered as a trademark in 1893 and by 1895 it was being sold in every state and territory in the United States. In 1899, The Coca-Cola Company began franchised bottling operations in the United States. \n\nCoca-Cola might owe its origins to the United States, but its popularity has made it truly universal. Today, you can find Coca-Cola in virtually every part of the world.",
"can_post": true,
"checkins": 77,
"talking_about_count": 215181
}
example for GoDaddy.com: http://graph.facebook.com/GoDaddy
{
"id": "8749090685",
"name": "GoDaddy.com",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/276455_8749090685_6602072_s.jpg",
"link": "https://www.facebook.com/GoDaddy",
"likes": 107451,
"category": "Internet/software",
"website": "http://GoDaddy.com/ http://twitter.com/GoDaddy http://youtube.com/GoDaddy http://www.linkedin.com/companies/godaddy.com ",
"username": "GoDaddy",
"company_overview": "Go Daddy helps people and businesses create and grow their online presence. Go Daddy is the world's dominant domain registrar, is also the top hosting provider in North America and the world's #1 provider of new SSL certificates. Go Daddy develops most all of its 52+ product offerings. Go Daddy has more than 7 million active customers worldwide and provides 24/7 industry-best customer service. The company is U.S. based and doesn't outsource or off-shore a single job.",
"products": "http://GoDaddy.com/Domains\nhttp://GoDaddy.com/Hosting\nhttp://GoDaddy.com/Email\nhttp://GoDaddy.com/SSL",
"can_post": true,
"talking_about_count": 2727
}
However, an fd:admin should be a USER id, not a PAGE id. You can use the graph API explorer to find out your USER id. Go to: https://developers.facebook.com/tools/explorer