Created
July 8, 2016 12:13
-
-
Save kintero/7d902f95e2a364862775c56679c477a2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#' osm_geocoder | |
#' | |
#' geocodes a location using OpenStreetMap. | |
#' | |
#' @param location a character string or list specifying a location of interest. | |
#' @return data.frame with variables lon and lat | |
#' @seealso \url{http://wiki.openstreetmap.org/wiki/Nominatim} | |
osm_geocoder <- function(location) { | |
library(jsonlite) | |
location<-gsub(' ', "+", location) | |
url_string <- paste0('http://nominatim.openstreetmap.org/search?format=json&addressdetails=0&limit=1&q=', location) | |
list<-sapply(url_string, fromJSON) | |
lat<-NULL | |
lon<-NULL | |
if (length(url_string)>1){ | |
# Get Latitude | |
lat<-lapply(list, '[[', "lat") | |
lat<-lapply(lat, FUN = function(x){ | |
ifelse(is.null(x), NA, x) | |
}) | |
lat<-unlist(lat) | |
# Get Longitude | |
lon<-lapply(list, '[[', "lon") | |
lon<-lapply(lon, FUN = function(x){ | |
ifelse(is.null(x), NA, x) | |
}) | |
lon<-unlist(lon)}else{ | |
names(list)<-attr(list, "dimnames")[[1]] | |
# Get Latitude | |
lat<-list$lat | |
lat<-lapply(lat, FUN = function(x){ | |
ifelse(is.null(x), NA, x) | |
}) | |
lat<-unlist(lat) | |
# Get Longitude | |
lon<-list$lon | |
lon<-lapply(lon, FUN = function(x){ | |
ifelse(is.null(x), NA, x) | |
}) | |
lon<-unlist(lon) | |
} | |
df<-data.frame(lat=lat, lon=lon) | |
rownames(df)<-NULL | |
return(df) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment