Skip to content

Instantly share code, notes, and snippets.

@jansim
Last active August 21, 2020 10:52
Show Gist options
  • Save jansim/00d6eb047697659de0ca25552a4169dc to your computer and use it in GitHub Desktop.
Save jansim/00d6eb047697659de0ca25552a4169dc to your computer and use it in GitHub Desktop.
🌐 Get country information (name, iso3, continent) from geospatial coordinates (latitude and longitude) in R without contacting an external API
library(sp)
library(rworldmap)
#' Get country from coordinates
#' based on: https://stackoverflow.com/questions/14334970/convert-latitude-and-longitude-coordinates-to-country-name-in-r/14342127#14342127
#'
#' @param lng Contains the longitude in degrees
#' @param lat Contains the latitude in degrees
#' @param export What to return, options: 'name' => country name (default), 'iso3' => ISO3 country code, 'continent6' => continent (6 continent model), 'continent7' => continent (7 continent model), 'raw' => whole spatial indices object
#'
#' @return Country information selected in 'export' (defaults to country name)
#' @export
#'
#' @examples
#' coords2country(lat = c(52.3667), lng = c(4.8945))
#' coords2country(lat = c(52.3667), lng = c(4.8945), export = 'iso3')
coords2country = function(lat, lng, export = 'name') {
points <- data.frame(lng, lat) # create point dataframe as requested with longitude then latitude
countriesSP <- getMap(resolution='low')
#countriesSP <- getMap(resolution='high') #you could use high res map from rworldxtra if you were concerned about detail
# convert our list of points to a SpatialPoints object
# pointsSP = SpatialPoints(points, proj4string=CRS(" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
#setting CRS directly to that from rworldmap
pointsSP = SpatialPoints(points, proj4string=CRS(proj4string(countriesSP)))
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
switch (export,
name = indices$ADMIN, # return the ADMIN names of each country
iso3 = indices$ISO3, # returns the ISO3 code
continent6 = indices$continent, # returns the continent (6 continent model)
continent7 = indices$REGION, # returns the continent (7 continent model)
raw = indices, # return the raw indices object with everything
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment