I am writing a script that takes an input KML file, created in google earth, and plots a grid of coordinate points inside of the polygon.
So far, I have the polygon input and a grid of points for the bounding box of the polygon, but I want to have only points INSIDE the polygon.
I tried to do this using the over() function, but it is not working. Suggestions?
You can download my test KML file 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")
I'm going to show a solution using library(sf), which is the successor to 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)
To view the objects on the map I'm using my googleway package that plots it on a Google Map (therefor you need an API key), but you can use leaflet or whatever map you want
library(googleway)
set_key("your_api_key_here")
google_map() %>%
add_polygons(my.poly) %>%
add_markers(my.points)

You can use the function sf::st_join() to join geometries
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)
Here, pointsInside is all the points that are within the polygon
google_map() %>%
add_polygons(my.poly) %>%
add_markers(pointsInside)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With