##install.packages("dplyr")
##install.packages("leaflet")

library("dplyr")
library("leaflet")

## geocoding function using OSM Nominatim API
## details: http://wiki.openstreetmap.org/wiki/Nominatim
## made by: D.Kisler 

nominatim_osm <- function(address = NULL)
{
  if(suppressWarnings(is.null(address)))
    return(data.frame())
  tryCatch(
    d <- jsonlite::fromJSON( 
      gsub('\\@addr\\@', gsub('\\s+', '\\%20', address), 
           'http://nominatim.openstreetmap.org/search/@addr@?format=json&addressdetails=0&limit=1')
    ), error = function(c) return(data.frame())
  )
  if(length(d) == 0) return(data.frame())
  return(data.frame(lon = as.numeric(d$lon), lat = as.numeric(d$lat)))
}


adresy <- seznam_lokalit$Adresa

adresy_souradnice <- suppressWarnings(lapply(adresy, function(address) {
api_output <- nominatim_osm(address)
return(data.frame(adresy = address, api_output))}) %>%
  bind_rows() %>% 
  data.frame())

adresy_souradnice$nazev <- seznam_lokalit$Název

leaflet(data = adresy_souradnice) %>% addTiles() %>% addMarkers(~lon, ~lat)