Search code examples
ropenstreetmap

Search cities using OpenStreetMap and R


I want to get the GPS coordinate for each cities in a list using OpenStreetMap in R. I base my code on this very nice example.

The only difference is that I want to add county name to city name and country code. Here is my code below:

cities = data.frame(nom=c("Toulouse", "Paris", "Égletons", "Marseille", 
                          "Clermont Ferrand"), region=c("Haute-Garonne", "Paris", "Corrèze", 
                          "Bouches-du-Rhône", "Puy-de-Dôme"), pays=rep("FR",5))


locateCountry = function(nameCity, nameCounty, codeCountry) {
  cleanCityName = gsub(' ', '%20', nameCity)
  cleanCountyName = gsub(' ', '%20', nameCounty)
  url = paste(
    "http://nominatim.openstreetmap.org/search?city="
    , cleanCityName
    , "&county="
    , cleanCountyName
    , "&countrycodes="
    , codeCountry
    , "&limit=9&format=json"
    , sep="")
  resOSM = fromJSON(url)
  if(length(resOSM) > 0) {
    return(c(resOSM[[1]]$lon, resOSM[[1]]$lat))
  } else return(rep(NA,2)) 
}

coords <- t(apply(cities, 1, function(aRow) locateCountry(aRow[1], aRow[2])))

Unfortunately I get the following message:

Error in paste("http://nominatim.openstreetmap.org/search?city=", cleanCityName,  : 
  argument "codeCountry" is missing, with no default 

I am also looking for a way to merge the extracted coordinates coords and cities.

Can anyone help?


Solution

  • Answer:

    library(OpenStreetMap)
    library(RJSONIO)
    
    
    cities = data.frame(nom=c("Toulouse", "Paris", "Égletons", "Marseille", 
                              "Clermont Ferrand"), region=c("Haute-Garonne", "Paris", "Corrèze", 
                              "Bouches-du-Rhône", "Puy-de-Dôme"), pays=rep("FR",5),
                        effectif=c(20,5,15,3,3))
    print(cities)
    
    locateCountry = function(nameCity, nameCounty, codeCountry) {
      cleanCityName = gsub(' ', '%20', nameCity)
      cleanCountyName = gsub(' ', '%20', nameCounty)
      url = paste(
        "http://nominatim.openstreetmap.org/search?city="
        , cleanCityName
        , "&county="
        , cleanCountyName
        , "&country="
        , "FR"
        , "&limit=9&format=json"
        , sep="")
      resOSM = fromJSON(url)
      if(length(resOSM) > 0) {
        return(c(resOSM[[1]]$lon, resOSM[[1]]$lat))
      } else return(rep(NA,2)) 
    }
    
    coords <- t(apply(cities, 1, function(aRow) locateCountry(aRow[1], aRow[2])))
    
    cities$lat <- coords[,1]
    cities$lon <- coords[,2]