I wrote a function to determine if a given lat/lon point falls within a specific polygon from the tz_world.shp file. I pass in lon = -77, lat = 42, which is in New York State. The ID from the 155th entry is 'America/New_York'. But, the use of point.inpoly returns a zero-row length object. Here is my code. Please help. Thanks. 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)
The screen-view of the coords shows typical bounding lon/lat points for NYS, which should surround my supplied lon/lat point.
Here's an alternative approach:
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>