Search code examples
rr-leaflet

How can I use the AllMaps leaflet plugin with R?


Leaflet allows one to use custom map tile URLs. Here's an example from the docs.

library(leaflet)

leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 4) %>%
  addWMSTiles(
    "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
    layers = "nexrad-n0r-900913",
    options = WMSTileOptions(format = "image/png", transparent = TRUE),
    attribution = "Weather data © 2012 IEM Nexrad"
  )

The tool AllMaps allows users to georeference raster images and then create an XYZ tile server from those images. They have created a leaflet plugin. Here is an example from the docs.

import L from 'leaflet'
import { WarpedMapLayer } from '@allmaps/leaflet'

const map = L.map('map', {
  center: [51.052785, 3.730803],
  zoom: 14,
  zoomAnimationThreshold: 1
})

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 18,
  attribution: '&copy; <a href=https://www.openstreetmap.org/copyright>OpenStreetMap</a> contributors'
}).addTo(map)

const annotationUrl = 'https://annotations.allmaps.org/manifests/8f9faeba73d67031'
const warpedMapLayer = new WarpedMapLayer(annotationUrl)
  .addTo(map)

My question: Is it possible to use the leaflet R package to display tiles from AllMaps as shown in the example directly above?


Solution

  • Yes, this is possible. Here is an R implementation of your example above by extending Leaflet with the plugin.

    library(leaflet)
    library(htmltools)
    library(htmlwidgets)
    
    allMapsPlugin <- htmlDependency(
      "@allmaps_leaflet", "1.0.0",
      src = c(href = 'https://cdn.jsdelivr.net/npm/@allmaps/[email protected]/dist/bundled'), 
      script = 'allmaps-leaflet-1.9.umd.min.js'
    )
    
    registerPlugin <- function(map, plugin) {
      map$dependencies <- c(map$dependencies, list(plugin))
      map
    }
    
    leaflet() |> 
      addTiles() |> 
      setView(lat = 51.054450, lng = 3.724924, zoom = 13) |> 
      registerPlugin(allMapsPlugin) |> 
      onRender("function(el, x) {
                  const annotationUrl = 'https://annotations.allmaps.org/manifests/8f9faeba73d67031'
                  const warpedMapLayer = new L.WarpedMapLayer(annotationUrl)
                        .addTo(this)
                }")
    

    enter image description here