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.
- We start by loading the leaflet.js,
domandwebsocketlibraries.leaflet.jsis used to create a mapdomis used to create the container hosting the map, andwebsocketis needed to enable control of the map with R.
- The container is created with the
divcommand and rendered on the screen using therenderfunction.- An
idis 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.
- An
- The leaflet map and a tile layer are then added following the leaflet.js quickstart guide.
ui.R#
Control the leaflet map with R#
1. Start a WebSocket connection#
We start a WebSocket connection using the following commands:
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.
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.
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.