I am trying to create a polygon grid to plot in leaflet, but am running into an error that I cannot seem to figure out:
library(leaflet)
library(raster)
library(sf)
library(rgdal)
r <- raster(ext = extent(-10,0, -5, 5), res=c(1,1))
p <- rasterToPolygons(r)
p <- st_as_sf(p)
leaflet() %>%
addTiles() %>%
addPolygons(p)
I get the error:
Error in derivePolygons(data, lng, lat, missing(lng), missing(lat), "addPolygons") :
addPolygons must be called with both lng and lat, or with neither.
I know that this is being thrown by the addPolygons()
call, but I cannot seem to figure out what is doing it or how to fix it.
You are passing the polygon object in your leaflet::addPolygons()
call by position; it will be passed to the second argument (since we are in a pipe).
The second position argument is lng
for longitude. As a result your leaflet object will have longitude specified, and latitude missing.
What you need to do is pass the object by name = as data
argument. This can happen both in your addPolygons()
call or in the base leafet()
call.
library(leaflet)
library(raster)
library(sf)
library(rgdal)
r <- raster(ext = extent(-10, 0, -5, 5), res=c(1,1))
p <- rasterToPolygons(r)
p <- st_as_sf(p)
leaflet() %>%
addTiles() %>%
addPolygons(data = p) # see what I have done? :)