Chapter 8 Helpful Tips
8.1 Adding more basemaps
Leaflet has a number of basemaps you can use as backgrounds to your maps. We can add these additional basemaps using the addProviderTiles()
function. Within this function, we specify the name of a basemap that Leaflet recognizes, then we provide the group=
argument to give each basemap a display name. The addLayersControl()
function serves to create a "legend" at the top right of the interactive map where the user may select a basemap; within this function we specify the names of our basemaps that we designated in the group
argument of the addProviderTiles()
function. Check out the code below and explore the different basemap options. For more information, visit the Leaflet for R webpage.
leaflet() %>%
# add different provider tiles
addProviderTiles("OpenStreetMap",
# give the layer a name
group = "OpenStreetMap") %>%
addProviderTiles("Stamen.Toner",
group = "Stamen.Toner") %>%
addProviderTiles("Stamen.Terrain",
group = "Stamen.Terrain") %>%
addProviderTiles("Esri.WorldStreetMap",
group = "Esri.WorldStreetMap") %>%
addProviderTiles("CartoDB.Positron",
group = "CartoDB.Positron") %>%
addProviderTiles("Esri.WorldImagery",
group = "Esri.WorldImagery") %>%
# add a layers control
addLayersControl(
baseGroups = c("OpenStreetMap", "Stamen.Toner",
"Stamen.Terrain", "Esri.WorldStreetMap",
"CartoDB.Positron", "Esri.WorldImagery"),
# position it on the topleft
position = "topleft")
8.2 Changing the size of the map window
We can easily change the default map window size using the fitBounds()
function. Within this function we provide the coordinates for our window (lng1, lat1 and lng2, lat2).
leaflet() %>%
addTiles() %>%
fitBounds(lng1 = -65.5,
lat1 = 18.5,
lng2 = -67.1,
lat2 = 17.9)
8.3 Adding a measuring tool
Leaflet has many features to customize your maps. One additional feature is the measurement tool, which the user can use to measure the distance between two points. To add the measurement tool to a map, create a new layer using addMeasure()
. This function has additional arguments so that you can further customize its features. For example, specifying the argument primaryLengthUnit = "meters"
will change the distance measurement to output the distance in meters. To view the different options for customizing the measurement tool type ?addMeasure
into the console or visit the reference material.
leaflet() %>%
addTiles() %>%
fitBounds(lng1 = -65.5,
lat1 = 18.5,
lng2 = -67.1,
lat2 = 17.9) %>%
addMeasure(primaryLengthUnit = "meters")
8.4 How to launch your interactive map on the internet
After you have created your interactive map using R, you may publish this map on the internet using several methods. Resources outlining this procude can be found here: