Skip to content

Instantly share code, notes, and snippets.

@aghaynes
Created June 11, 2018 12:00
Show Gist options
  • Save aghaynes/a057bd88ae5183eb1703c9455c19bfbc to your computer and use it in GitHub Desktop.
Save aghaynes/a057bd88ae5183eb1703c9455c19bfbc to your computer and use it in GitHub Desktop.
Code to create a buffer around points, linking nearby points together via buffers
library(osmdata)
library(rgdal) ; library(maptools) ; library(rgeos)
q0 <- opq(bbox = "Bern, Switzerland", timeout = 60)
q1 <- add_osm_feature(q0, key = 'building', value = "hospital")
x <- osmdata_sp(q1)
library(leaflet)
spChFIDs(x$osm_polygons) <- 1:nrow(x$osm_polygons@data)
cent <- gCentroid(x$osm_polygons, byid = TRUE)
leaflet(cent) %>% addTiles() %>% addCircles()
buff <- gBuffer(cent, byid = TRUE, width = 0.0015)
leaflet(cent) %>% addTiles() %>% addPolygons(data = buff, col = "red") %>% addCircles()
buff <- SpatialPolygonsDataFrame(buff, data.frame(row.names = names(buff), n = 1:length(buff)))
gt <- gIntersects(buff, byid = TRUE, returnDense = FALSE)
ut <- unique(gt)
nth <- 1:length(ut)
buff$n <- 1:nrow(buff)
buff$nth <- NA
for(i in 1:length(ut)){
x <- ut[[i]]
buff$nth[x] <- i
}
buffdis <- gUnaryUnion(buff, buff$nth)
leaflet(cent) %>% addTiles() %>% addPolygons(data = buffdis, col = "red") %>% addCircles()
gt <- gIntersects(buffdis, byid = TRUE, returnDense = FALSE)
ut <- unique(gt)
nth <- 1:length(ut)
buffdis <- SpatialPolygonsDataFrame(buffdis, data.frame(row.names = names(buffdis), n = 1:length(buffdis)))
buffdis$nth <- NA
for(i in 1:length(ut)){
x <- ut[[i]]
buffdis$nth[x] <- i
}
buffdis <- gUnaryUnion(buffdis, buffdis$nth)
leaflet(cent) %>% addTiles() %>% addPolygons(data = buffdis, col = "red") %>% addCircles()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment