In his article Kyle Walker showed a method to make Voronoi Polygons in Leaflet. He drew Voronoi polygons around each starbucks coffeehouse in Fort Worth by means of the following code:
library(leaflet); library(rgeos)
library(rgdal); library(spatstat)
library(maptools)
starbucks <- read.csv('starbucks.csv')
fw <- subset(starbucks, City == 'Fort Worth')
coords <- cbind(fw$Longitude, fw$Latitude)
## Spatial points w/the WGS84 datum
sp_fw <- SpatialPointsDataFrame(coords = coords, data = fw,
proj4string = CRS("+proj=longlat +datum=WGS84"))
sp_fw_proj <- spTransform(sp_fw, CRS("+init=epsg:26914"))
fw_coords <- sp_fw_proj@coords
## Create the window for the polygons
window <- owin(range(fw_coords[,1]), range(fw_coords[,2]))
## Create the polygons
d <- dirichlet(as.ppp(fw_coords, window))
## Convert to a SpatialPolygonsDataFrame and calculate an "area" field.
dsp <- as(d, "SpatialPolygons")
dsp_df <- SpatialPolygonsDataFrame(dsp,
data = data.frame(id = 1:length(dsp@polygons)))
proj4string(dsp_df) <- CRS("+init=epsg:26914")
dsp_df$area <- round((gArea(dsp_df, byid = TRUE) / 1000000), 1)
dsp_xy <- spTransform(dsp_df, CRS("+proj=longlat +datum=WGS84"))
## Map it!
leaflet() %>%
addMarkers(data = fw,
lat = ~ Latitude,
lng = ~ Longitude,
popup = fw$Name) %>%
addPolygons(data = dsp_xy,
color = "green",
fill = "green",
popup = paste0("Area: ",
as.character(dsp_xy$area),
" square km")) %>%
addTiles()
I want to add an extra feature to his map: I want to assign a specific color to a polygon. This color depends on the characteristics of the nearest marker (the centroid).
for example, color every polygon with a starbucks centroid "green", and with a Dunkin' Donuts centroid "purple". (assuming that the starbucks.csv also includes coordinates of Dunkin' Donuts)
In other words, I want to merge the data of a centroid ("fw") with that of the polygon it belongs to ("dsp_xy").
Can someone help me out in this one?