You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

R语言调用Google Maps API获时长时遇NOT FOUND状态问题求助

Troubleshooting the Google Maps API NOT FOUND Error in Your R Function

Let’s walk through why you’re seeing that NOT FOUND error and fix your function to get reliable travel duration data:

1. The Immediate Fix: Complete Your API Request URL

Looking at your code snippet, the strQuery string gets cut off mid-destination parameter (destinat...). The Google Maps Directions API requires a full, properly formatted URL with all mandatory parameters to process your request—an incomplete URL will almost always throw a NOT FOUND error.

2. Full Corrected Function

I’ve updated your code to fix the URL structure, add proper error handling, and extract the duration data you need. Here’s the polished version:

getDuration <- function(from, to, tMode, key){ 
  # Convert to UTF-8 and URL-encode parameters to handle special characters
  from <- URLencode(iconv(from, to="UTF-8"))
  to <- URLencode(iconv(to, to="UTF-8"))
  tMode <- URLencode(iconv(tMode, to="UTF-8"))
  
  # Build the complete, valid API request URL
  strQuery <- paste0(
    "https://maps.googleapis.com/maps/api/directions/json?",
    "origin=", from,
    "&destination=", to,
    "&mode=", tMode,
    "&key=", key
  )
  
  # Send the request and check for HTTP-level errors
  library(httr)
  response <- GET(strQuery)
  if (http_status(response)$category != "Success") {
    stop("Request failed: ", http_status(response)$message)
  }
  
  # Parse the JSON response from the API
  result <- content(response, as = "parsed")
  
  # Check for API-specific errors (e.g., invalid key, missing permissions)
  if (result$status != "OK") {
    stop("API Error: ", result$status, " - ", result$error_message)
  }
  
  # Extract duration data (uses the first route/leg; adjust if you need alternatives)
  duration_text <- result$routes[[1]]$legs[[1]]$duration$text
  duration_seconds <- result$routes[[1]]$legs[[1]]$duration$value
  
  return(list(duration = duration_text, duration_seconds = duration_seconds))
}

3. Additional Troubleshooting Steps

If you still run into issues after fixing the URL, check these common culprits:

  • API Key Permissions: Make sure your Google Cloud API key has the Directions API enabled, and there are no IP/usage restrictions blocking your request.
  • Valid Travel Mode: Ensure tMode is one of the allowed values: driving, walking, bicycling, or transit—using an invalid mode will trigger errors.
  • Test the URL Manually: Print out the strQuery value and paste it into a browser. The raw API response will show you exact error details (like invalid origin/destination) that might not surface in your R code at first.

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

火山引擎 最新活动