Skip to content

Instantly share code, notes, and snippets.

@kintero
Created July 8, 2016 12:13
Show Gist options
  • Save kintero/7d902f95e2a364862775c56679c477a2 to your computer and use it in GitHub Desktop.
Save kintero/7d902f95e2a364862775c56679c477a2 to your computer and use it in GitHub Desktop.
#' 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