0

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.

Benjamin Levy
  • 333
  • 6
  • 19

1 Answers1

2

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>
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • over( SpatialPoints( data.frame( lon = -77, lat = 42 ) ) ) gives error: Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘over’ for signature ‘"SpatialPoints", "missing"’ – Benjamin Levy Aug 18 '16 at 22:14
  • I see what you did, but your use of over() assumes that we know the shp index (e.g., America/New_York). But, what I want is the name of the shape index such that the given lat/lon point falls in the correct set of lat/lon coordinates from the shp file. This implies at least a 'while' loop, – Benjamin Levy Aug 18 '16 at 22:29
  • I suggest editing your original post. Please read [how to provide minimal reproducible examples in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610). Then edit & improve it accordingly. A good post usually provides minimal input data, the desired output data & code tries - all copy-paste-run'able in a new/clean R session. I cannot reproduce your error (update packages?). And I don't see what you result should look like. – lukeA Aug 19 '16 at 08:26