我正在编写一个脚本,该脚本采用在Google地球中创建的输入KML文件,并在多边形内部绘制坐标点网格。
到目前为止,我有多边形输入和多边形边界框的点网格,但我想在多边形中只有点。
我尝试使用over()
函数执行此操作,但它无效。建议?
您可以下载我的测试KML文件HERE。
library(rgdal)
library(sp)
library(maptools)
# ogrInfo() to find layer name... not as labelled in Google Earth?!
my.poly = readOGR(ds = "PolyNYC.kml", layer = "PolyNYC")
proj4string(my.poly) <- "+proj=longlat +datum=WGS84 +no_defs"
# Creating grid of points
grdpts <- makegrid(my.poly)
# Converting from df to spdf
coords = cbind(grdpts$x1, grdpts$x2)
sp = SpatialPoints(coords)
spdf = SpatialPointsDataFrame(coords, grdpts, proj4string = CRS(proj4string(my.poly)))
# Using over() to select only those points in the polygon
inPoly = over(spdf, my.poly)
# This is not working
# Plotting the polygon with the points overlaid.
plot(my.poly)
points(spdf, pch = 3, col = "red")
#kmlPoints(obj = spdf, kmlfile = "BBoxFromPoly.kml", kmlname = "Testing123")
答案 0 :(得分:5)
我将使用library(sf)
展示解决方案,library(sp)
library(sf)
## read the kml
my.poly <- sf::st_read("~/Downloads/PolyNYC.kml")
## create a grid of points
grdpts <- sf::st_make_grid(my.poly, what = "centers")
## convert it to an `sf` object, as opposed to an `sfc`
my.points <- sf::st_sf(grdpts)
要查看地图上的对象,我正在使用我的googleway软件包将其绘制在Google地图上(因此您需要API密钥),但您可以使用leaflet
或任何您想要的地图
library(googleway)
set_key("your_api_key_here")
google_map() %>%
add_polygons(my.poly) %>%
add_markers(my.points)
您可以使用函数sf::st_join()
来连接几何
pointsInside <- sf::st_join(x = my.points, y = my.poly, left = FALSE)
# Simple feature collection with 59 features and 2 fields
# geometry type: POINT
# dimension: XY
# bbox: xmin: -74.1754 ymin: 40.63513 xmax: -73.75675 ymax: 40.8514
# epsg (SRID): 4326
# proj4string: +proj=longlat +datum=WGS84 +no_defs
# First 10 features:
# Name Description geometry
# 1 TestLayerNYC POINT (-74.08237 40.63513)
# 2 TestLayerNYC POINT (-74.03585 40.63513)
# 3 TestLayerNYC POINT (-74.1754 40.65916)
# 4 TestLayerNYC POINT (-74.12889 40.65916)
# 5 TestLayerNYC POINT (-74.08237 40.65916)
# 6 TestLayerNYC POINT (-74.03585 40.65916)
# 7 TestLayerNYC POINT (-73.80326 40.65916)
# 8 TestLayerNYC POINT (-74.1754 40.68319)
# 9 TestLayerNYC POINT (-74.12889 40.68319)
# 10 TestLayerNYC POINT (-74.08237 40.68319)
此处,pointsInside
是多边形
google_map() %>%
add_polygons(my.poly) %>%
add_markers(pointsInside)