user3091668
user3091668

Reputation: 2310

Finding countries latitude and longitude in the R map class

I am trying to mark with a point some countries in a world map using R.

    # World map is available in the maps package
    library(maps)
    library(dplyr)
    
    # No margin
    par(mar=c(0,0,0,0))
    
    # World map
    m <- map('world',
        col="#f2f2f2", fill=TRUE, bg="white", lwd=0.05,
        mar=rep(0,4),border=0, ylim=c(-80,80) 
    )

# Get coordinates        
brazil <- c(m$x[which(m$names=="Brazil")], m$y[which(m$names=="Brazil")])
netherlands <- c(m$x[which(m$names=="Netherlands")], m$y[which(m$names=="Netherlands")])

# Data frame 
data <- rbind(brazil, netherlands) %>% 
  as.data.frame()
colnames(data) <- c("long","lat")

# No margin
    par(mar=c(0,0,0,0))
     map('world',
        col="#f2f2f2", fill=TRUE, bg="white", lwd=0.05,
        mar=rep(0,4),border=0, ylim=c(-80,80) 
    )
    points(x=data$long, y=data$lat, col="slateblue", cex=3, pch=20)

However, the points are far from the requested countries. enter image description here

Any ideas to point out the countries correctly?

Upvotes: 1

Views: 877

Answers (1)

Dave2e
Dave2e

Reputation: 24069

There is not a one to one ratio between the counties names and the x & y values in the maps data structure.

For example:

str(m)
List of 4
 $ x    : num [1:100375] -69.9 -69.9 -69.9 -70 -70.1 ...
 $ y    : num [1:100375] 12.5 12.4 12.4 12.5 12.5 ...
 $ range: num [1:4] -180 190 -80 80
 $ names: chr [1:1599] "Aruba" "Afghanistan" "Angola" "Angola:Cabinda" ...
 - attr(*, "class")= chr "map"

There are 1599 names and over 100,000 x-y pairs.

Here is an approach of finding the countries of interest, extracting that information and then finding the midpoint from the range values. Close enough at this resolution.
You may want to add exact=TRUE to the maps function to isolate down to the main geographic area of the country and remove the outlying islands and territories. The US is a good example to apply this option to.

# World map is available in the maps package
library(maps)

# World map
m <- map('world',
         col="#f2f2f2", fill=TRUE, bg="white", lwd=0.05,
         mar=rep(0,4),border=0, ylim=c(-80,80), plot=FALSE
)

# Get coordinates        
brazil <- map('world', regions = "brazil", plot=FALSE, exact=TRUE)
  brazil_long <- mean(brazil$range[1:2])
  brazil_lat <- mean(brazil$range[3:4])

netherlands <- map('world', regions = "Netherlands", plot=FALSE)    
  netherland_long <- mean(netherlands$range[1:2])
  netherland_lat <- mean(netherlands$range[3:4])

# Data frame 
data <- data.frame(long = c(brazil_long, netherland_long), lat= c(brazil_lat, netherland_lat))

# No margin
par(mar=c(0,0,0,0))
map('world',
    col="#f2f2f2", fill=TRUE, bg="white", lwd=0.05,
    mar=rep(0,4),border=0, ylim=c(-80,80) 
)
points(x=data$long, y=data$lat, col="slateblue", cex=3, pch=20)

enter image description here

Upvotes: 1

Related Questions