Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Projected coordinate reference systems in Leaflet and R

Tags:

r

gis

leaflet

As per the documentation, leaflet in R supports projected coordinate reference systems. I cannot make this work, however.

Given any sf polygon object in projected coordinate system EPSG:27700 (called myprojectedsfobject), running the code block below the screen shot is given with the error commented in the code.

crs <- leafletCRS(
                  code = "EPSG:27700",
                  proj4def =
                    "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs")

leaflet(options = leafletOptions(crs = crs)) %>%
  addPolygons(data = myprojectedsfobject, label = ~htmlEscape(NAME_3), fill = FALSE)
#Warning messages:
#1: sf layer is not long-lat data 
#2: sf layer has inconsistent datum (+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 #+y_0=-100000 +ellps=airy +units=m +no_defs).
#Need '+proj=longlat +datum=WGS84' 

enter image description here

Can anyone help with how to correctly implement projected coordinate systems in leaflet in R?

like image 382
RDavey Avatar asked Oct 29 '25 09:10

RDavey


1 Answers

From the documentation https://rstudio.github.io/leaflet/projections.html, it looks like you still need to provide WGS84 Lat Long data, then leaflet will project to the CRS you want.

From the documentation above:

"While tiles must be in the same projection as used in the leafletCRS function, you must always use WGS 84 longitude/latitude data for markers, circles, polygons, and lines. Leaflet will automatically project the coordinates when displaying."

Below are epsg:27700 tiles, and epsg:4326 markers which are transformed to 27700 by leaflet automatically.

epsg27700 <- leafletCRS(crsClass = "L.Proj.CRS", code = "EPSG:27700",
                       proj4def = "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs",
                       resolutions = c(896.0, 448.0, 224.0, 112.0, 56.0, 28.0, 14.0, 7.0, 3.5, 1.75),#2^(13:-1), # 8192 down to 0.5
                       origin = c(-238375.0, 1376256.0)
)


# EPSG:27700 TILE LAYER
tile_url <- "https://api.os.uk/maps/raster/v1/zxy/Leisure_27700/{z}/{x}/{y}.png?key=iJIgGUXKYFiT2s2ejG7cAB0sGuvtOCyp"

leaflet(options = leafletOptions( crs = epsg27700)) %>%
  addTiles(urlTemplate = tile_url)%>%
  
  # WGS84 Markers are transformed to EPSG:27700 behind the scenes
  addMarkers(-0.16359, 51.5083)   
like image 82
Jumble Avatar answered Oct 31 '25 23:10

Jumble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!