1

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?

SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
Grigory Sharkov
  • 121
  • 1
  • 8
  • If you try it with the places starting with `E` rather than `É` it seems to work. It might be an encoding problem or just a quirk of the Google API. You can use `iconv(...,to="ASCII//TRANSLIT")` to remove all accents from characters. – Andrew Gustar Apr 18 '18 at 16:02
  • Étampes doesn't seem to be URL encoded correctly. This URL using "%C3%89tampes" returns a result: https://maps.googleapis.com/maps/api/directions/json?origin=%C3%89tampes&destination=Cours%20Valmy%2C%20Nanterre&mode=driving – Preston Apr 18 '18 at 22:32

1 Answers1

0

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
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139