Search code examples
rgisr-sprgdalr-leaflet

leaflet() draws shapefile as giant rectangle


I'm running into a problem with leaflet where it is drawing a giant rectangle instead of the shapes. I'm certain there is some issue with the format of the shapefile, but I can't determine what's going wrong. Plotting the file works fine.

file: https://upload.cat/8c8ade09a3489b47

original file source: http://sites.psu.edu/psucz/data/ (at bottom of page)

require(tidyverse)
require(leaflet)
require(rgdal)


ers_shp <- readOGR("ERS10.shp")

#Doesn't work, produces rectangle:
leaflet() %>% addProviderTiles("CartoDB.Positron") %>% addPolygons(data = ers_shp)

#Works, indicating the data is there.
plot(ers_shp, col="#f2f2f2", fill=TRUE, bg="skyblue", lwd=0.25, mar=rep(0,4), border=0 )

Solution

  • This is because you need to convert the polygons to lat/long before passing them to leaflet:

    library(sf)
    inv <- sf::st_read("ERS10.rep.shp") %>% 
      sf::st_transform(4326)
    leaflet() %>% addProviderTiles("CartoDB.Positron") %>% addPolygons(data = inv)
    

    OR

    library(sp)
    inv <- rgdal::readOGR("ERS10.rep.shp") %>%  
      spTransform(CRS("+proj=longlat +datum=WGS84"))
    leaflet() %>% addProviderTiles("CartoDB.Positron") %>% addPolygons(data = inv)