rgoogle-maps-api-3map-directions

Google maps api status NOT FOUND R


I created my function for accessing Google maps API. I am trying to find out how long does it take from different points to a target location.

getDuration <- function(from,to,tMode,key){

  from <- iconv(from, to="UTF-8")
  to <- iconv(to, to="UTF-8")
  tMode <- iconv(tMode, to="UTF-8")

  from <- URLencode(from)
  to <- URLencode(to)
  tMode <- URLencode(tMode)

  strQuery <- paste0(
                      "https://maps.googleapis.com/maps/api/directions/json?",
                      paste0("origin=",from),
                      paste0("&","destination=",to),
                      paste0("&","mode=",tMode),
                      paste0("&key=",key)
                    )

  print(strQuery)
  jDist <- fromJSON(strQuery,simplifyDataFrame = T)

  if (jDist$status != "OK"){
    print(paste0("Bad status: ",jDist$status))
    return(NA)
  }

  if (length(jDist$routes)==0){
    print("no route")
    return(NA)
  }

  if (length(jDist$routes$legs)==0){
    print("no legs")
    return(NA)
  }
  return(jDist$routes$legs[[1]]$duration$value)
}

Then I am trying to apply this function to a character vector "from":

from

[1] "Étampes" "Étréchy" "Dourdan" "La Ferté-Alais" "Méréville" "Saint-Chéron"

sapply(from,function(x) { getDuration(x,to,"driving",key) })

The output I get is the following:

       Étampes        Étréchy        Dourdan La Ferté-Alais      Méréville   Saint-Chéron 
        NA             NA           3501           4280             NA             NA 

It is strange because route between Étampes and my target destination exists and it is not empty: https://maps.googleapis.com/maps/api/directions/json?origin=%C3%83%E2%80%B0tampes&destination=Cours%20Valmy,%20Nanterre&mode=driving&key=AIzaSyBrmNaCXH_ppK7F0uW4SXZhPIBoDLQdKFE

Does anybody knows how to identify the root of problem?


Solution

  • This problem doesn't appear to exist if you use googleway

    library(googleway)
    
    set_key("GOOGLE_API_KEY")
    
    res <- google_directions(
        origin = "Étampes",
        destination = "cours valmy"
    )
    
    direction_legs(res)$distance
    #      text value
    # 1 62.6 km 62648
    
    direction_legs(res)$duration
    #            text value
    # 1 1 hour 8 mins  4065