Google Maps Distance Matrix API request per day - google-maps

I can call Google Maps Distance Matrix API in two ways:-
1) with single origins zip code and single destinations zip code
eg: https://maps.googleapis.com/maps/api/distancematrix/json?origins=48084&destinations=48326&key=" + API_KEY
2) with array of origins zip code and array destinations zip code
eg : https://maps.googleapis.com/maps/api/distancematrix/json?origins=48084%7C48098%7C48309&destinations=48326%7C48306&key=" + API_KEY
1) How the request/day is counted in case 1 and case 2?
2) Can I save the distance and time locally in the cache of DB for performance benefit ?

Case1: Here you are using single origin and single destination.So,
If you are want multiple conversions then you need to hit
this api multiple times which incurs multiple request.
origin destination #Request
A B 1
A C 1
-------------------------------------------------------------
Total Request 2
Case2: In this case you can achieve multiple conversions with a single
api hit,means its just single request.
orgin destination #Request
A B,C 1
--------------------------------------------------------------
Total Request 1
Conclusion: Case2 is less expensive in terms of no of api request

Related

Distance matrix api for Google

I am using Google Distance Matrix API. But I am unable to figure out the API cost, it has written on their website that "price per element". So, if I have two origins and 1000 destinations, then what will be my total API cost, and is the example program with Google OR tools is enough to run 1000 destination distance API call and solve the matrix?
Please Help!!
Each Distance Matrix API call generates a number of elements (the number of origins times the number of destinations, e.g. 10 origins * 10 destinations = 100 elements) and each element costs $0.005 as per Google's documentation. So in the provided example, you'd be billed 0.005 * 100 = $0.5 per call to the Distance Matrix API.
Also, note that you cannot add two origins and 1000 destinations to a single request. You are limited to a maximum of 25 origins or 25 destinations per request, hence in order to query 1,000 destinations you'd need to make multiple Distance Matrix API requests.
Hope this helps!

Why I keep getting an error of MAX_ELEMENTS_EXCEEDED when I don't overpass the daily free number of requests?

So I developed a code where I read a file with some locations (15 to be more precise), where the first one is the depot and the other 14 locations are the places where a bus needs to pass to collect patients. In order to do that, I use Google Maps API key in order to collect the real distances and write them in a .txt file in the end.
import pandas as pd
import googlemaps
from itertools import tee
import numpy as np
#Read CSV file into data frame named 'df'
#change seperator (sep e.g. ',') type if necessary
df = pd.read_csv("D:/Utilizadores/Documents/FEUP/2018-2019/1º Semestre/PDI/Relatório/locais2.txt", sep='\\t',
engine='python', skiprows=[0], names=["address", "latitude", "longitude"])
lat = np.expand_dims(np.array(df["latitude"]), 1)
lon = np.expand_dims(np.array(df["longitude"]), 1)
coordinates = np.concatenate((lat, lon), axis=1)
coordinates = list(coordinates)
coordinates = [list(coor) for coor in coordinates]
#Perform request to use the Google Maps API web service
#API_key = 'AIzaSyCi8DDz_CCiVwW2JtvT6i-XpJYiEwxFryI'
API_key = 'AIzaSyCpumDcRbbteV64xlGOUQ5_Bah8Ja5gdJ4'
gmaps = googlemaps.Client(key=API_key)
result = gmaps.distance_matrix(coordinates, coordinates, mode='driving')["rows"]
distance_matrix = np.zeros((len(result), len(result)))
for i in range(len(result)):
for j in range(len(result)):
distance_matrix[i, j] = result[i]["elements"][j]["distance"]["value"]
np.savetxt("D:/Utilizadores/Documents/FEUP/2018-2019/1º Semestre/PDI/Relatório/locais_output.txt", distance_matrix, delimiter=",", fmt='%d')
print(distance_matrix)
The distances I want are from one place to every place, so the result I want is a matrix of 15x15 where the diagonal is filled with 0's. But it keeps printing this error:
"googlemaps.exceptions.ApiError: MAX_ELEMENTS_EXCEEDED".
The only way to not have an error is to put a limit on the reading of the file of 10 locations, including the depot:
result = gmaps.distance_matrix(coordinates[0:10], coordinates[0:10], mode='driving')["rows"]
Why is that? Anyone?
from the documentation
MAX_ELEMENTS_EXCEEDED indicates that the product of origins and destinations exceeds the per-query limit.
from "usage and billing":
Each query sent to the Distance Matrix API generates elements, where the number of origins times the number of destinations equals the number of elements.
Other Usage Limits
While you are no longer limited to a maximum number of elements per day (EPD), the following usage limits are still in place for the Distance Matrix API:
Maximum of 25 origins or 25 destinations per request.
Maximum 100 elements per server-side request.
Maximum 100 elements per client-side request.
1000 elements per second (EPS), calculated as the sum of client-side and server-side queries.
15 x 15 = 225 which is greater than the maximum allowed (100)
That you don't want or need some of the responses is not relevant.

If you make a single googlemaps API request with multiple origin/dest addresses, does that count as a single request?

Since there is a free quota of 2500, I am wondering if there's anything I could do to optimize the number of requests I make to the API.
If I make a single request with 1 origin address & 2 destination addresses, does that count as 2 requests in terms of the quota?
Thank you
The answer to your question is NO, In Distance Matrix API you have a usage limit of 2500 free elements per day (Standard Plan)[2].
where the:
Nº of Elements = Nº Origins x Nº Destinations [1]
and you can have:
A maximum of 25 origins or 25 destinations per request.
A Maximum 100 elements per request.
A Maximum 100 elements per second*, calculated as the sum of client-side and server-side queries.[2]
[1] https://developers.google.com/maps/faq#usage_quotacalc
[2] https://developers.google.com/maps/documentation/javascript/distancematrix#UsageLimits

How to request Waypoints in Google Map Distance Matrix API?

I want to use Google Map Distance Matrix API but I also want to include Waypoints in it.
Distance matrix take 2 inputs only as it takes list of Starting Points and list of Destinations points. I want to include Starting Point, Destination Point and Final Destination Point.
So it should show distance matrix of A -> B -> C
How can I incorporate that ?
Use A and B as origins.
Use B and C as destinations.
Your response should contain A->B, A->C, B->B, B->C distances.
Extract & sum A->B and B->C to receive your target distance with a single API call.

Using google maps API to find average speed at a location

I am trying to get the current traffic conditions at a particular location. The GTrafficOverlay object mentioned here only provides an overlay on an existing map.
Does anyone know how I can get this data from Google using their API?
It is only theorical, but there is perhaps a way to extract those data using the distancematrix api.
Method
1)
Make a topological road network, with node and edge, something like this:
Each edge will have four attributes: [EDGE_NUMBER;EDGE_SPEED;EDGE_TIME,EDGE_LENGTH]
You can use the openstreetmap data to create this network.
At the begining each edge will have the same road speed, for example 50km/h.
You need to use only the drivelink and delete the other edges. Take also into account that some roads are oneway.
2)
Randomly chose two nodes that are not closer than 5 or 10km
Use the dijsktra shortest path algorithm to calculate the shortest path between this two nodes (the cost = EDGE_TIME). Use your topological network to do that. The output will look like:
NODE = [NODE_23,NODE_44] PATH = [EDGE_3,EDGE_130,EDGE_49,EDGE_39]
Calculate the time needed to drive between the two nodes with the distance matrix api.
Preallocate a matrix A of size N X number_of_edge filled with zero value
Preallocate a matrix B of size 1 X number_of_edge filled with zero value
In the first row of matrix A fill each column (corresponding to each edge) with the length of the edge if the corresponding edge is in the path.
[col_1,col_2,col_3,...,col_39,...,col_49,...,col_130]
[0, 0, len_3,...,len_39,...,len_49,...,len_130] %row 1
In the first row of matrix B put the time calculated with the distance matrix api.
Then select two news node that were not used in the first path and repeat the operation until that there is no node left. (so you will fill the row 2, the row 3...)
Now you can solve the linear equation system: Ax = B where speed = 1/x
Assign the new calculated speed to each edge.
3)
Iterate the point 2) until your calculated speed start to converge.
Comment
I'm not sure that the calculated speed will converge, it will be interesting to test the method.I will try to do that if I got some time.
The distance matrix api don't provide a traveling time more precise than 1 minute, that's why the distance between the pair of node need to be at least 5 or 10 or more km.
Also this method fails to respect the Google's terms of service.
Google does not make available public API for this data.
Yahoo has a feed (example) with traffic conditions -- construction, accidents, and such. A write-up on how to access it is here.
If you want actual road speeds, you will probably need to work with a commercial provider.