Unable to get correct ETA using Google Maps API - google-maps

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!

Related

Google Place Search does not return result

I need to fetch location data based on given text.
As example if I search Aldi in google map it shows me lot of data with pagination. I need to get that result using google places api.
I tried it with two API calls. But it returns me following result
https://maps.googleapis.com/maps/api/place/textsearch/json?query=Aldi&key=MY_KEY
Result
{
"html_attributions" : [],
"results" : [],
"status" : "ZERO_RESULTS"
}
https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=ALDI&inputtype=textquery&fields=place_id,name,formatted_address,geometry&key=MY_KEY
Result
{
"candidates" : [],
"status" : "ZERO_RESULTS"
}
I need to fetch data based on the given name. Can anyone find out the reason.
There are three types of searches provided by the Places API: Find Place, Nearby Search and Text Search. Each allows you to specify a location with radius to start the search from. The location is specified as a latitude/longitude pair. You received ZERO_RESULTS because you didn't specify a location for your request. If the location parameter is not specified "the API uses IP address biasing by default" according to the documentation. So, there are no Aldi stores within range of the location of your IP address.
Find Place will only return one result though, in my experience, it sometimes returns two. Both Nearby Search and Text Search will return up to 60 place results. All three of the Place search requests allow specifying a radius around your location of up to 50 kilometers. If you need to find Aldi places worldwide you'll need to make quite a few requests.
I am weeks into a similar project to find all locations for a list of restaurant chains in the US. I have found that Nearby Search is a better choice for my use case and should be considered always before committing to Text Search for a project. I've tested Aldi searches with both Nearby Search and Text Search and found that they provide the identical set of place_id results. This Nearby Search request will find all Aldi locations within 50 kilometers of New York City:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.785276%2C-73.9651827&name=Aldi&radius=50000&key=MY_API_KEY
Here is the same as a Text Search:
https://maps.googleapis.com/maps/api/place/textsearch/json?query=Aldi&location=40.785276%2C-73.9651827&radius=50000&key=MY_API_KEY
So why should we care? Text Search according to API documentation "... returns all of the available data fields for the selected place, and you will be billed accordingly." Furthermore "... the Text Search service is subject to a 10-times multiplier. That is, each Text Search request that you make will count as 10 requests against your quota." A Nearby Search request is less expensive and not subject to the 10x multiplier. It returns a subset of the available data fields that you might find sufficient. If you need additional data fields, you can get only what you need from a Places Detail request. Do the math for your application before you select Text Search. It might be dramatically less expensive to implement using Nearby Search followed by Places Detail requests if necessary. In any case, you don't want to be shocked when you hit quota limits unexpectedly because of the 10x multiplier OR the billed transaction costs are more than you expect!
I have found additional hurdles that should be considerations for projects attempting to find all locations for a business in a large area:
The Places API will prefer places within your radius but will include places outside your radius if it determines they are relevant and within the 60 place limit. I have had places returned more than 450 kilometers from my requested search position.
Results are going to be returned for places with names that are NOT what you searched for. In my search for the restaurant Benihana in Seattle a Nearby Search request only returns a restaurant with the name Hamansu. Upon investigation, this is because there is not a Benihana in Seattle, however, Hamansu is similar to Benihana in that it serves Japanese dishes grilled tableside. The API documentation states your search term will be "matched against all content that Google has indexed for this place, including but not limited to name, type, and address, as well as customer reviews and other third-party content."
Results are returned 20 at a time. If there are more results, a page_token is provided to make a request to get the next page of up to 20 results. Each request is chargeable. You will be billed for the 3 requests required to get 60 results. I'm not saying this is bad, just be aware of the expense and quota usage you are incurring with this API.
If there are more than 60 results for your radius then you haven't found all the possible locations within it. And, you can't determine with certainty what the effective radius covered was for the 60 results. You need to search with a small enough radius to return < 60 results for each request. A worldwide search is going to require a large quota and $ budget to pursue.
You should be aware that Places API search is not designed to provide results world wide. In your examples you specify only text value 'Aldi'. However, in order to get results you should specify also where you are searching.
For example, if I want to bias results towards Barcelona area in Spain I have to add location and radius in my request
https://maps.googleapis.com/maps/api/place/textsearch/json?query=Aldi&location=41.3850639%2C2.1734035&radius=10000&key=MY_API_KEY
This request will return Aldi supermarkets in Barcelona area as shown in my screenshot
The same thing for Find place, you should specify location bias
https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Aldi&inputtype=textquery&fields=formatted_address,geometry,name,place_id&locationbias=circle%3A1000%4041.3850639%2C2.1734035&key=MY_API_KEY
Also note that Find place returns only one result.
I hope this addresses your doubt.
#Art answer, which is marked with higher upvotes, is only partially correct. The answer suggests that the Find Place api (e.g. maps/api/place/findplacefromtext) will usually return 1 result, at most 2. I tend to agree with him. Even if your search hits multiple targets, only one would be returned with the Find Place api. Consequently, he recommends to use Nearby Search or Text Search, both of which would yield at most 60 results.
However, these two searches require some form of location parameter, otherwise they will likely return 0 results, defaulting to using your IP address, as he indicates. But he recommends using a location accompanied with a radius parameter. The problem with this is the radius parameter has a maximum limit. So it will not target all types of things you want if you are searching over the stretch of an entire country, such as the United States.
The truth is you do not need to use the location and radius. There is another option called region. And you can use region to search the entire distance of a country.
What #Art suggested:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=25.7392%2C-80.3103&name=Law%Offices%of%Alex&radius=50000&key=KEY
https://maps.googleapis.com/maps/api/place/textsearch/json?query=Law%Offices%of%Alex&location=25.7392%2C-80.3103&radius=50000&key=KEY
A more encompassing alternative:
https://maps.googleapis.com/maps/api/place/textsearch/json?query=Law%Offices%of%Alex&region=us&key=KEY
You need to specify the location of your search.

Difference between duration and duration_in_traffic in Google Directions API Response

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.

Google map - which are local and utc time?

I have this timezone result from google map, for instance,
{
"dstOffset" : 0.0,
"rawOffset" : -28800.0,
"status" : "OK",
"timeZoneId" : "America/Los_Angeles",
"timeZoneName" : "Pacific Standard Time"
}
which one is local time and which one is utc time?
dstOffset: the offset for daylight-savings time in seconds. This will be zero if the time zone is not in Daylight Savings Time during the specified timestamp.
rawOffset: the offset from UTC (in seconds) for the given location. This does not take into effect daylight savings.
Calculating the Local Time:
The local time of a given location is the sum of the timestamp parameter, and the dstOffset and rawOffset fields from the result.
The Google Time zone API

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?

Does the Google Directions API use UTC or Local Time?

I am developing a transit navigation app using the Google Directions API.
The API requires me to submit a departure time (departure_time) for transit queries.
Is it necessary to convert the local time to UTC time for this parameter?
I could not validate it through the API's response, as there is no accurate time returned in it.
That Doc Was In Error
Apparently the Google team writing that doc page made an error and later fixed it.
The number you report 1343605500 is no longer found on that page. Today the number on that page is 1343641500. I suspect you did indeed see that number on that page previously. Googling (ironically enough) for site:https://developers.google.com 1343605500 does list that page as a hit. Apparently the hit is based on a cached copy of the old erroneous page. Even Google cannot escape the reach of Google.
Work in UTC/GMT
Is it necessary to convert the local time to UTC time for this parameter?
Yes.
The API works with GMT/UTC (no time zone offset), which only makes sense when you think about it. Almost always, the best practice for handling date-time is to perform your business logic, serialization, database records, and so on in UTC, then convert to local time only for presentation to the user.
Just looking at the example URL itself suggests it is in UTC. The only possible reference to a local time zone would be the word "Brooklyn" which is certainly not a clear unique identifier for a time zone.
http://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens&sensor=false&departure_time=1343641500&mode=transit
And of course the doc says the API uses UTC/GMT:
the desired time of departure as seconds since midnight, January 1, 1970 UTC
Poor Writing
The confusion stems from the poor writing in that documentation page. They need to append a crucial "UTC" or "GMT" to that "9:45 am". Mentioning New York and 9:45 in the same breath implies local time, whereas that example is truly 5:45 in the morning local time in Brooklyn.
The below request searches for Transit Directions from Brooklyn, New York to Queens, New York. When requesting transit directions, be sure to specify either a departure_time or arrival_time.
Note that in this example the departure time is specified as July 30, 2012 at 09:45 am. Update the parameter to a point in the future before submitting the request.
Old Versus New Numbers
Old number: 1343605500 (reported in the answer by davidg, and by googling)
New number: 1343641500 (found 2013-12)
Number if they had actually meant 9:45 in New York: 1343655900.
Example Code
I don't do JavaScript. So instead, I present some Java code using the sophisticated Joda-Time 2.3 date-time handling library running in Java 7. I use both the old (erroneous) and new (correct) numbers to show the date-time in both UTC and New York time zones. Furthermore, I calculate the number of seconds since epoch would have been used to get to 9:45 am July 30 2012 in New York, to produce a third number of seconds.
The Google API uses seconds, while Joda-Time uses milliseconds, so I multiply or divide by a thousand.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
DateTimeZone timeZone_NewYork = DateTimeZone.forID( "America/New_York" );
// On this page:
// https://developers.google.com/maps/documentation/directions/#ExampleRequests
// …look for the following two paragraphs…
// --
// The below request searches for Transit Directions from Brooklyn, New York to Queens, New York. When requesting transit directions, be sure to specify either a departure_time or arrival_time.
// Note that in this example the departure time is specified as July 30, 2012 at 09:45 am. Update the parameter to a point in the future before submitting the request.
// --
// Below that text, find this URL:
// http://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens&sensor=false&departure_time=1343641500&mode=transit
// Extract that departure time of 1,343,641,500 seconds since the Unix Epoch of beginning of 1970 UTC.
// Apparently in the past that page erroneously used the number 1343605500 where today it uses 1343641500.
// Use the correct number found on that page today, 2013-12-25: 1343641500.
DateTime dateTimeInUtcWithNewNumber = new DateTime ( ( 1343641500L * 1000L ), DateTimeZone.UTC );
DateTime dateTimeInNewYorkWithNewNumber = dateTimeInUtcWithNewNumber.toDateTime( timeZone_NewYork );
System.out.println( "dateTimeInUtcWithNewNumber: " + dateTimeInUtcWithNewNumber );
System.out.println( "dateTimeInNewYorkWithNewNumber: " + dateTimeInNewYorkWithNewNumber );
// Use the old erroneous number previously found on that page: 1343605500.
DateTime dateTimeInUtcWithOldNumber = new DateTime ( ( 1343605500L * 1000L ), DateTimeZone.UTC );
DateTime dateTimeInNewYorkWithOldNumber = dateTimeInUtcWithOldNumber.toDateTime( timeZone_NewYork );
System.out.println( "dateTimeInUtcWithOldNumber: " + dateTimeInUtcWithOldNumber );
System.out.println( "dateTimeInNewYorkWithOldNumber: " + dateTimeInNewYorkWithOldNumber );
// Calculating the number that should have been used if the Google team had actually meant 9:45 AM local time in New York: 1343655900.
DateTime dateTimeInNewYork_2012_07_30_09_45 = new DateTime ( 2012, 7, 30, 9, 45, 0, timeZone_NewYork );
System.out.println( "dateTimeInNewYork_2012_07_30_09_45: " + dateTimeInNewYork_2012_07_30_09_45 );
System.out.println( "dateTimeInNewYork_2012_07_30_09_45 in seconds since Unix epoch: " + ( dateTimeInNewYork_2012_07_30_09_45.getMillis() / 1000L ) );
When run…
dateTimeInUtcWithNewNumber: 2012-07-30T09:45:00.000Z
dateTimeInNewYorkWithNewNumber: 2012-07-30T05:45:00.000-04:00
dateTimeInUtcWithOldNumber: 2012-07-29T23:45:00.000Z
dateTimeInNewYorkWithOldNumber: 2012-07-29T19:45:00.000-04:00
dateTimeInNewYork_2012_07_30_09_45: 2012-07-30T09:45:00.000-04:00
dateTimeInNewYork_2012_07_30_09_45 in seconds since Unix epoch: 1343655900