Skip to main content

Interact with leaflet map from R

Created: 2021-05-22. Modified: 2021-05-22.

Introduction#

In this article, we will look at how to interact with leaflet map from R. This provides a starting point to perform live spatial analysis with R. Here is a demo:

Create a page with a leaflet map#

We will use the setting default_2_deparsers() for this application.

  1. We start by loading the leaflet.js, dom and websocket libraries.
    • leaflet.js is used to create a map
    • dom is used to create the container hosting the map, and
    • websocket is needed to enable control of the map with R.
  2. The container is created with the div command and rendered on the screen using the render function.
    • An id is assigned to it for potential future reference.
    • The height styling is applied; this is mandatory or it may assume a height of 0. 100vh refers to “100% viewport height”, which is the full height of the viewable area.
  3. The leaflet map and a tile layer are then added following the leaflet.js quickstart guide.

ui.R#

#! config(deparsers = default_2_deparsers())
#! load_script("https://unpkg.com/leaflet@1.7.1/dist/leaflet.css")
#! load_script("https://unpkg.com/leaflet@1.7.1/dist/leaflet.js")
#! load_library("dom")
#! load_library("websocket")
# Create a div element to put the map
render(div(id = "mapid", style = 'height:100vh;'))
# Set up a map
mymap <- L::map('mapid')$
setView(latlng = c(-37.8136, 144.9631), zoom = 10)
# Add tile layer to the map
L::tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
list(maxZoom = 18,
attribution = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors')
)$addTo(mymap)

Control the leaflet map with R#

1. Start a WebSocket connection#

We start a WebSocket connection using the following commands:

library(sketch)
conn <- websocket$new()
conn$startServer()

2. Refresh the app#

After the server is started, refresh / restart the app to establish the connection. If it is successful, a message will display at the R console.

> library(sketch)
> conn <- websocket$new()
> conn$startServer()
Server started.
$type
[1] "WebSocket.onopen"
$message
[1] "App connected."

3. Control the leaflet map#

Once the connection is started, use conn$sketch_mode() to enter the sketch mode, and from here, you can directly manipulate the map! Here are some sample commands.

# Zoom in
mymap$flyTo(latlng = c(-37.8136, 144.9631), zoom = 15)
# Move toward south and zoom in
mymap$flyTo(latlng = c(-37.8350, 144.9600), zoom = 17)
# Add a marker
L::marker(c(-37.8350, 144.9600))$addTo(mymap)
# Back to original point and zoom out
mymap$flyTo(latlng = c(-37.8136, 144.9631), zoom = 13)

Result#

Note that all commands from the leaflet.js library are available. See here for the full list.

4. Clean up#

Once you are finished with the map, use conn$stopServer() to close the WebSocket connection.