Google Apps Script调用Google Maps API持续失败求助
Hey Mike, that intermittent error is definitely frustrating—let’s break down why it’s happening and how to fix it, plus how to confirm your API key is working.
Why the Error Happens
The TypeError: Cannot read property "legs" from undefined pops up because sometimes the Google Maps Directions API isn’t returning any valid routes when you call getDirections(). When that happens:
directions["routes"]becomes an empty array- Trying to access
routes[0]gives youundefined - Then trying to get
legsfrom that undefined value throws the error
This is intermittent because the failure isn’t consistent—it could be due to temporary API glitches, quota limits hitting, or issues with your API key configuration.
How to Fix the Error (and Prevent Crashes)
First, add error handling to your code to gracefully handle cases where no routes are returned. This will stop the error and let you debug what’s going wrong. Here’s an updated version of your function:
function mikeDistance(start, end){ start = "CV4 8DJ"; end = "cv4 9FE"; var maps = Maps; maps.setAuthentication("#####", "#####"); var dirFind = maps.newDirectionFinder(); dirFind.setOrigin(start); dirFind.setDestination(end); var directions = dirFind.getDirections(); // Check if any routes were returned if (!directions.routes || directions.routes.length === 0) { // Log the full response to debug why no routes came back Logger.log("No routes found. Full API response: " + JSON.stringify(directions)); return "No route available"; // Or return 0/null based on your needs } var firstRoute = directions.routes[0]; // Check if the route has valid legs data if (!firstRoute.legs || firstRoute.legs.length === 0) { Logger.log("No legs data in route. Route details: " + JSON.stringify(firstRoute)); return "Invalid route data"; } var rawDistance = firstRoute.legs[0].distance.value; var distance = rawDistance/1609.34; return distance; }
How to Confirm Your API Key is Being Recognized
To verify your key is working:
- Run the function, then open the Logs (click
View > Logsin the Apps Script editor) - Look for the logged response when an error occurs:
- If you see an
error_messagelike"The provided API key is invalid"or"API key not authorized for this API", your key isn’t set up correctly - If there’s no error but
routesis empty, the key is being recognized—you’re hitting another issue like quota limits or temporary API downtime
- If you see an
Additional Troubleshooting Steps
- Check Google Cloud Console Settings:
- Make sure your API key has the Maps Directions API enabled (search for it in the API Library and toggle it on)
- Verify your key’s application restrictions: If you set restrictions, ensure Google Apps Script is allowed (for testing, you can temporarily set restrictions to "None" to rule this out)
- Check your quota usage: Go to the Quotas tab for the Directions API—if you’re hitting the free limit, requests will start failing intermittently
- Rule Out Address Issues:
While your hardcoded addresses look valid, try testing with other well-known addresses to see if the error still happens (this can confirm if the issue is address-related or API-related) - Handle Rate Limits:
If you’re calling this function multiple times quickly, you might hit the API’s rate limits. Add a small delay between requests (usingUtilities.sleep(1000)for 1 second) if you’re batch-processing requests.
内容的提问来源于stack exchange,提问作者MikeCoverUps




