I have a Google Sheet where we are fetching the driving distance between two Lat/Lng via the Maps Service. The function below works, but the matrix is 4,500 cells, so I'm getting the "Hit Limit" error.
How can I supply my paid account's API key here?
Custom Function
function drivingMeters(origin, destination) {
if (origin=='' || destination==''){return ''}
var directions = Maps.newDirectionFinder()
.setOrigin(origin)
.setDestination(destination)
.getDirections();
return directions.routes[0].legs[0].distance.value ;
}
Example use:
A1: =drivingMeters($E10,G$9)
Where E10 = 42.771328,-91.902281
and G9 = 42.490390,-91.1626620
Per documentation, you should initialize the Maps service with your authentication details prior to calling other methods:
I recommend storing these values in
PropertiesService
and usingCacheService
, to provide fast access. Using this approach, rather than writing them in the body of your script project, means they will not be inadvertently copied by other editors, pushed to a shared code repository, or visible to other developers if your script is published as a library.Furthermore, I recommend rewriting your custom function to accept array inputs and return the appropriate array output - this will help speed up its execution. Google provides an example of this on the custom function page: https://developers.google.com/apps-script/guides/sheets/functions#optimization
Example with use of props/cache: