rprojectionr-leaflet

Drawing numerous polygons


I am trying to draw numerous polygons with the leaflet package but I can't understand what's going wrong.

The shapefile I use can be found here: https://www.data.gouv.fr/en/datasets/fond-de-carte-des-codes-postaux/

library(leaflet)
library(rgdal)
df <- readOGR("C:/Users/me/codes_postaux","codes_postaux_region")
plot(df)

output shapefile

The shapefile seems ok to me and the code I use is rather simple. However I only get the map as an output and no Polygons. I've been struggling with this issue for quite a long time, I would really appreciate if someone could help me here.

map <- leaflet(df) %>%
  addProviderTiles("CartoDB.Positron")%>%
  fitBounds(10,38,10,55) %>% 
  addPolygons(fillOpacity = 0.8, color = "Blue", weight = 1)

map

leaflet


Solution

  • Look at df@proj4string and the output of plot(df); axis(1); axis(2). Your shapefile uses a specific CRS. You need to transform your SpatialPolygonsDataFrame with a common CRSobj (I got the CRS code from here: Leaflet for R: Raster Images).

    library(sp)
    
    pj <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
    df2 <- spTransform(df, pj)
    
    map2 <- leaflet(df2) %>%
      addProviderTiles("CartoDB.Positron")%>%
      fitBounds(10,38,10,55) %>% 
      addPolygons(fillOpacity = 0.8, color = "Blue", weight = 1)
    map2
    

    enter image description here