R中国家代码的纬度经度坐标

问题描述:

有没有一种快速的方法可以将纬度和经度坐标转换为R中的州代码?我一直在使用zipcode包作为查找表,但是当我查询很多经/纬度值时,它太慢了

Is there a fast way to convert latitude and longitude coordinates to State codes in R? I've been using the zipcode package as a look up table but it's too slow when I'm querying lots of lat/long values

如果不在R中,可以使用Google Geocoder或任何其他类型的快速查询服务来做到这一点吗?

If not in R is there any way to do this using google geocoder or any other type of fast querying service?

谢谢!

这里是一个函数,它在较低的48个状态内获取经纬度的data.frame,并针对每个点返回其所处的状态.

Here is a function that takes a data.frame of lat-longs within the lower 48 states, and for each point, returns the state in which it is located.

大多数函数只是简单地准备sp包中over()函数所需的SpatialPointsSpatialPolygons对象,这对计算点和多边形的交点"确实很繁重:

Most of the function simply prepares the SpatialPoints and SpatialPolygons objects needed by the over() function in the sp package, which does the real heavy lifting of calculating the 'intersection' of points and polygons:

library(sp)
library(maps)
library(maptools)

# The single argument to this function, pointsDF, is a data.frame in which:
#   - column 1 contains the longitude in degrees (negative in the US)
#   - column 2 contains the latitude in degrees

latlong2state <- function(pointsDF) {
    # Prepare SpatialPolygons object with one SpatialPolygon
    # per state (plus DC, minus HI & AK)
    states <- map('state', fill=TRUE, col="transparent", plot=FALSE)
    IDs <- sapply(strsplit(states$names, ":"), function(x) x[1])
    states_sp <- map2SpatialPolygons(states, IDs=IDs,
                     proj4string=CRS("+proj=longlat +datum=WGS84"))

    # Convert pointsDF to a SpatialPoints object 
    pointsSP <- SpatialPoints(pointsDF, 
                    proj4string=CRS("+proj=longlat +datum=WGS84"))

    # Use 'over' to get _indices_ of the Polygons object containing each point 
    indices <- over(pointsSP, states_sp)

    # Return the state names of the Polygons object containing each point
    stateNames <- sapply(states_sp@polygons, function(x) x@ID)
    stateNames[indices]
}

# Test the function using points in Wisconsin and Oregon.
testPoints <- data.frame(x = c(-90, -120), y = c(44, 44))

latlong2state(testPoints)
[1] "wisconsin" "oregon" # IT WORKS