How to get the longitude and latitude coordinates from a city name and country in R?

Jochem picture Jochem · Dec 16, 2012 · Viewed 18.2k times · Source

I have a long list of city names and countries and I would like to plot them on a map. In order to do this I need the longitude and latitude information of each of the cities.

My table is called test and has the following structure:

Cityname  CountryCode
New York  US
Hamburg   DE
Amsterdam NL

Answer

Jochem picture Jochem · Dec 16, 2012

With the following code I have successfully solved the problem.

library(RJSONIO)
nrow <- nrow(test)
counter <- 1
test$lon[counter] <- 0
test$lat[counter] <- 0
while (counter <= nrow){
  CityName <- gsub(' ','%20',test$CityLong[counter]) #remove space for URLs
  CountryCode <- test$Country[counter]
  url <- paste(
    "http://nominatim.openstreetmap.org/search?city="
    , CityName
    , "&countrycodes="
    , CountryCode
    , "&limit=9&format=json"
    , sep="")
  x <- fromJSON(url)
  if(is.vector(x)){
    test$lon[counter] <- x[[1]]$lon
    test$lat[counter] <- x[[1]]$lat    
  }
  counter <- counter + 1
}

As this is calling an external service (openstreetmaps.org) it can take a while for larger datasets. However, you probably only do this once in a while when new cities have been added to the list.