Interact with leaflet map from R
Created: 2021-05-22. Modified: 2021-05-22.
#
IntroductionIn 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 mapWe will use the setting default_2_deparsers()
for this application.
- We start by loading the leaflet.js,
dom
andwebsocket
libraries.leaflet.js
is used to create a mapdom
is used to create the container hosting the map, andwebsocket
is needed to enable control of the map with R.
- The container is created with the
div
command and rendered on the screen using therender
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.
- 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 connectionWe start a WebSocket connection using the following commands:
#
2. Refresh the appAfter 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 mapOnce 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.
#
ResultNote that all commands from the leaflet.js library are available. See here for the full list.
#
4. Clean upOnce you are finished with the map, use conn$stopServer()
to close the
WebSocket connection.