有沒有一種快速的方法來將經度和緯度座標轉換爲R中的州代碼?我一直使用zipcode包作爲查找表,但當我查詢很多緯度/長度值時,它太慢緯度經度座標到R中的州代碼
如果不是在R有任何方式使用谷歌地理編碼器或任何其他類型快速查詢服務?
謝謝!
有沒有一種快速的方法來將經度和緯度座標轉換爲R中的州代碼?我一直使用zipcode包作爲查找表,但當我查詢很多緯度/長度值時,它太慢緯度經度座標到R中的州代碼
如果不是在R有任何方式使用谷歌地理編碼器或任何其他類型快速查詢服務?
謝謝!
這是一個函數,它在低48個狀態內採用lat-long的data.frame,併爲每個點返回它所在的狀態。
大部分功能的簡單準備由sp
包over()
函數,該函數計算的點和麪的「交集」的真正繁重所需的SpatialPoints
和SpatialPolygons
對象:
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([email protected], function(x) [email protected])
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
我必須將wgs84更改爲WGS84才能使此示例正常工作。 – lever 2016-03-08 23:11:19
@lever感謝您指出。不知道什麼時候(以及哪裏)發生了變化。無論如何,我現在編輯來解決它。 – 2016-03-08 23:17:27
請參閱sp包中的內容。您需要將狀態邊界作爲SpatialPolygonDataFrame。
你能做到這一點的R.
幾行library(sp)
library(rgdal)
#lat and long
Lat <- 57.25
Lon <- -9.41
#make a data frame
coords <- as.data.frame(cbind(Lon,Lat))
#and into Spatial
points <- SpatialPoints(coords)
#SpatialPolygonDataFrame - I'm using a shapefile of UK counties
counties <- readOGR(".", "uk_counties")
#assume same proj as shapefile!
proj4string(points) <- proj4string(counties)
#get county polygon point is in
result <- as.character(over(points, counties)$County_Name)
謝謝!這更簡單:) – 2016-08-04 13:18:02
這裏也看到我的答案,使用'ggmap :: revgeocode':https://stackoverflow.com/questions/46150851/how-to-get-california-縣位置從-LAT itude-and-long-information/46151310#46151310 – 2017-09-11 08:51:12