You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Google Apps Script调用Google Maps API持续失败求助

Troubleshooting Intermittent "Cannot read property 'legs' from undefined" Error in Google Apps Script Maps Tool

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 you undefined
  • Then trying to get legs from 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:

  1. Run the function, then open the Logs (click View > Logs in the Apps Script editor)
  2. Look for the logged response when an error occurs:
    • If you see an error_message like "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 routes is empty, the key is being recognized—you’re hitting another issue like quota limits or temporary API downtime

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 (using Utilities.sleep(1000) for 1 second) if you’re batch-processing requests.

内容的提问来源于stack exchange,提问作者MikeCoverUps

火山引擎 最新活动