I'm trying to add some boundaries to a leaflet map using the leaflet package in R. I write:
library(rgdal)
fw<-readOGR("/local/path/to/FWC_UT_MASTER_0623_2016.shp",verbose=FALSE)`
To add the polygons to leaflet, I write:
library(leaflet)
fw %>%
leaflet() %>%
addTiles() %>%
addPolygons(stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5)
It seems intuitive enough. I can't for the life of me figure why these little guys wont render. I thought the SpatialPolygonsDataFrame needed to be in WGS84. The original file is not.
..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
.. .. ..@ projargs: chr "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
So i tried reprojecting the original shapefile
fw.proj<-spTransform(fw, CRS("+init=epsg:4326"))
However,
fw.proj %>%
leaflet() %>%
addTiles() %>%
addPolygons(stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5)
renders a blank map as well. I saved the original shape file here: https://github.com/uky994/firewise
I'm surprised your readOGR
didn't issue any warnings, as the layer
argument is required.
But you're right that you need to transform the shape into lat/lon as this is what leaflet expects.
Here's some working code; you'll have to figure out the exact CRS
you want to use.
library(leaflet)
library(rgdal)
setwd("~/Downloads/firewise-master/")
fw <- readOGR(dsn = ".",
layer = "FWC_UT_MASTER_0623_2016",
verbose = FALSE)
fw_latlon <- spTransform(fw, CRS("+proj=longlat +datum=WGS84"))
leaflet() %>%
addTiles() %>%
addPolygons(data = fw_latlon)