Skip to content

Instantly share code, notes, and snippets.

@PhillRob
Last active August 29, 2015 14:24
Show Gist options
  • Save PhillRob/ffe9729cd33262cc42cc to your computer and use it in GitHub Desktop.
Save PhillRob/ffe9729cd33262cc42cc to your computer and use it in GitHub Desktop.
use google API to get match lon/lat data to country and state
reverseGeo <- function(latlng) {
require("XML")
require("httr")
latlng <- as.numeric(latlng)
latlngStr <- gsub(" ", "%20", paste(round(latlng, 2), collapse = ","))
url <- "http://maps.google.com"
path <- "/maps/api/geocode/xml"
query <- list(sensor = "false", latlng = latlngStr)
response <- GET(url, path = path, query = query)
if (response$status != 200) {
print(paste("HTTP Error:", response$status), quote = F)
return(c(NA, NA))
}
xml <- xmlInternalTreeParse(content(response, type = "text"))
status <- xmlValue(getNodeSet(xml, "//status")[[1]])
if (status != "OK") {
print(paste("Query Failed:", status), quote = F)
return(c(NA, NA))
}
xPath <- "//result[1]/address_component[type=\"country\"]/long_name[1]"
country <- xmlValue(getNodeSet(xml, xPath)[[1]])
xPath <- "//result[1]/address_component[type=\"administrative_area_level_1\"]/long_name[1]"
state <- xmlValue(getNodeSet(xml, xPath)[[1]])
return(c(state = state, country = country))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment