geocodeAddress <- function(address, result = 1, pause.time = 0.02) {
if (grepl("&", address)) {
address <- gsub("&", "", address)
}
address <- iconv(address, to = "ASCII//TRANSLIT")
root <- "http://maps.google.com/maps/api/geocode/json?address="
url <- URLencode(paste(root, address, "&sensor=false", sep = ""))
x <- RJSONIO::fromJSON(url, simplify = FALSE)
out <- list()
if (x$status == "OK") {
r <- result
# Centroid coordinates of first search result:
out$crd <- c(x$results[[r]]$geometry$location$lng,
x$results[[r]]$geometry$location$lat)
names(out$crd) <- c("lon", "lat")
# Data.frame of address components for checking:
name <- do.call(rbind, lapply(x$results[[r]]$address_components, function(y)
c(y$long_name, y$short_name)))
type <- sapply(x$results[[r]]$address_components, function(y)
paste(y$types, collapse=", "))
out$address <- data.frame(cbind(name, type))
out$address[] <- lapply(out$address, as.character)
names(out$address) <- c("long_name", "short_name", "type")
} else {
# If no result is found:
out <- list(crd = c(lon = NA, lat = NA),
address = data.frame(long_name = NA,
short_name = NA,
type = NA))
warning("Request Status: ", x$status)
}
Sys.sleep(pause.time)
return(out)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.