R:查找时区多边形中的点

时间:2016-08-18 20:27:51

标签: r dataframe shapefile point-in-polygon

我编写了一个函数来确定给定的lat / lon点是否属于tz_world.shp文件中的特定多边形。我传入lon = -77,lat = 42,这是在纽约州。第155个条目的ID是' America / New_York'。但是,使用point.inpoly会返回一个零行长度的对象。这是我的代码。请帮忙。谢谢。 BSL。

i = 155

timeZoneList = split( timeZonesShpFile, timeZonesShpFile$TZID )

ps = lapply( timeZoneList, Polygon )

p1 = lapply(seq_along(ps), function(i) Polygons(list(ps[[i]]), ID = names( timeZoneList )[i] ) )

my_spatial_polys = SpatialPolygons( p1, proj4string = CRS("+proj=longlat +datum=WGS84") )

polyNames = sapply(slot(my_spatial_spdf, 'polygons'), function(i) slot(i, 'ID'))

pt = SpatialPointsDataFrame(cbind(lon,lat), data.frame(row=1), proj4string=CRS("+proj=longlat +datum=WGS84" ))

thisPoly = my_spatial_polys[ i ]

thisList = getSpPPolygonsIDSlots( thisPoly )

thisDf = data.frame( row = 1, row.names = thisList )

thisSpdf = SpatialPolygonsDataFrame( thisPoly, thisDf )

pIp = point.in.poly( pt, thisSpdf )

> pIp

[1] coordinates row         row.1      
<0 rows> (or 0-length row.names)

coords的屏幕视图显示了NYS的典型边界lon / lat点,它应该包围我提供的lon / lat点。

1 个答案:

答案 0 :(得分:2)

这是另一种方法:

library(maptools)
library(rgdal)
library(rgeos)
download.file("http://efele.net/maps/tz/world/tz_world.zip", tf <- tempfile(fileext = ".zip"))
unzip(tf, exdir = tempdir())
shp <- readShapeSpatial(file.path(tempdir(), "world", "tz_world.shp"))
over(
  SpatialPoints(data.frame(lon = c(13, -77, 51), lat = c(52, 42, 0))), # Berlin, New York, London
  shp[shp$TZID %in% c("America/New_York", "Europe/Berlin"), ]
)
#               TZID
# 1    Europe/Berlin
# 2 America/New_York
# 3             <NA>