Pierre Dudek Pierre Dudek - 1 month ago 16
R Question

R / 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

Answer

Look at df@proj4string and the output of plot(df); axis(1); axis(2). Your shapefile uses a specific CRSobj. You need to convert your SpatialPolygonsDataFrame with basic CRSobj.

library(sp)

pj <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
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