JoFrhwld JoFrhwld - 1 year ago 61
R Question

Geocoding in R with Google Maps

I've tried running the code to geocode locations in R via Google Maps and the

package from this blog post:

Here are his functions:

getDocNodeVal=function(doc, path){
sapply(getNodeSet(doc, path), function(el) xmlValue(el))

doc = xmlTreeParse(u, useInternal=TRUE)
str=gsub(' ','%20',str)
lng=getDocNodeVal(doc, "/GeocodeResponse/result/geometry/location/lat")
lat=getDocNodeVal(doc, "/GeocodeResponse/result/geometry/location/lng")

When I run
, I get the following error:

> gGeoCode("Philadelphia, PA")
failed to load external entity "http%3A//,%20PA"
Error: 1: failed to load external entity "http%3A//,%20PA"

If I just paste into a browser the API url with
Philadelphia, PA
appended to the end, like the string passed to
, I get a result that looks like legitimate xml when I download it.

Is this an issue with the code, or have I failed to configure something or another?

Answer Source

Have you thought about using the json call instead? Looking at your code, you could achieve the same doing this (you'll need to install packages RCurl and RJSONIO from

Copy and paste this into R:


construct.geocode.url <- function(address, = "json", sensor = "false") {
  root <- ""
  u <- paste(root,, "?address=", address, "&sensor=", sensor, sep = "")

gGeoCode <- function(address,verbose=FALSE) {
  if(verbose) cat(address,"\n")
  u <- construct.geocode.url(address)
  doc <- getURL(u)
  x <- fromJSON(doc,simplify = FALSE)
  if(x$status=="OK") {
    lat <- x$results[[1]]$geometry$location$lat
    lng <- x$results[[1]]$geometry$location$lng
    return(c(lat, lng))
  } else {

Here's how you use the above functions:

x <- gGeoCode("Philadelphia, PA")

This is the result you get. I think in the original code, lat and lng are mixed up? But hopefully this is what you want:

> x
[1]  39.95233 -75.16379

Hope that helps a little mate,

Tony Breyal