Last active
August 29, 2015 14:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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