Search code examples
rleafletrgdal

Loading SpatialPolygonsDataFrame with Leaflet (for R) doesn't work


first of all I'm new to R so please bear with me.

What I'm eventually trying to accomplish is to show an interactive map of Amsterdam with Leaflet. For that I'm using RGDAL to read shapefiles.

This link contains the shapefiles of amsterdam.

I'm using the following code to read the shapefiles and to show the map.

amsterdam <- readOGR(".", layer = "sd2010zw_region", verbose = FALSE)

leaflet(amsterdam) %>%
  addProviderTiles("CartoDB.Positron", options= providerTileOptions(opacity = 0.99)) %>%
    addPolygons(
      stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5
    )

What I get is the map from CartoDB.Positron but not the 'polygonmap' as the second layer. What I get is a SpatialPolygonsDataFrame containing all sorts of data.

When I use the plot method on the other hand I get the map of Amsterdam

plot(amsterdam, axes=TRUE, border="gray")

But I don't want to use plots, I want to use Leaflet :)

What am I doing wrong here?


Solution

  • The problem is the projection. You need to project your data to longlat using spTransform from either rgdal or sp. Also, provide your SpatialPolygonsDataFrame in the addPolygons() call.

    library(leaflet)
    library(rgdal)
    
    amsterdam <- readOGR(".", layer = "sd2010zw_region", verbose = FALSE)
    
    ams_ll <- spTransform(amsterdam, CRS("+init=epsg:4326"))
    
    leaflet() %>%
      addProviderTiles("CartoDB.Positron", options= providerTileOptions(opacity = 0.99)) %>%
      addPolygons(data = ams_ll,
        stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5
      )