Search code examples
rleafletshapefilemap-projections

Render shapefile with no projection in leaflet map


I want to render a shapefile inside of a leaflet map.

This shapefile has no projection so I'm trying to give it one.

  directions <- readOGR("./directions/", "directions")
  proj4string(directions) <- CRS("+proj=longlat +datum=WGS84 +no_defs")

And after that I try to add it to my map like this:

  map <- leaflet() %>% 
    addProviderTiles("CartoDB.Positron") %>% 

    addPolygons(data=directions,weight=1,col = 'black') %>% 

    setView(lng = -3.8196207,
            lat = 40.4678698,
            zoom = 10)

The problem is that I get an error saying:

Geographical CRS given to non-conformant data: 450781.167295 4485221.863980

I tried using other projections as CRS like

  proj4string(directions) <- CRS("+proj=utm +zone=30 +ellps=GRS80 +units=m +no_defs")

which does not give me an error but the shapefile is not getting rendered either.

I don't really understand why that happens and how I can fix it.

BTW: I got this shapefile from a spanish website where traffic and airquality data gets published


Solution

  • You were very close. What you need to do is convert the projection from UTM Zone 17N to longitude and latitude projection.

    library(sp)
    library(rgdal)
    library(leaflet)
    
    # Read the shapefile
    directions <- readOGR("directions", "directions")
    # Set the projection to be UTM zone 30N
    proj4string(directions) <- CRS("+proj=utm +zone=30 +ellps=GRS80 +units=m +no_defs")
    # Conduct project transformation from UTM zone 30N to long-lat
    directions_longlat <- spTransform(directions, CRS("+proj=longlat +datum=WGS84 +no_defs"))
    
    map <- leaflet() %>% 
      addProviderTiles("CartoDB.Positron") %>% 
      addPolygons(data = directions_longlat, weight=1, col = 'black') %>% 
      setView(lng = -3.8196207,
              lat = 40.4678698,
              zoom = 10)
    map
    

    enter image description here