In this post, we will look at how to make interactive maps in R using the leaflet package. Interactive maps can be a powerful tool to communicate information.
Packages
We will start by loading the only package needed, leaflet.
# Load the leaflet library
library(leaflet)
For the initial examples, loading only this one package is enough.
Using Different Maps
You can load different types of maps using the addTiles() function. Below, we load the default map.
# Create a leaflet map with default map tile using addTiles()
leaflet() %>%
addTiles()
It is also possible to load other maps. To do this, you will use the addProviderTiles() function. Inside the parentheses, you must include the name of the map after the provider argument. In the example below, we load the “CartoDB” map.
leaflet() %>%
addProviderTiles(provider = "CartoDB")
We can extend what we have done so far by including location and zoom, as we will see.
Latitude, Longitude, and Zoom
It is also possible to set the latitude and longitude of the map along with the zoom level. In the code below, we set the coordinates to show the state of Texas, and we set the zoom to 6 so we can see individual city names using the setView() function.
# Texas on the Map with zoom of 6
leaflet() %>%
addProviderTiles("CartoDB") %>%
setView(lng = -99.9018, lat = 31.9686, zoom = 6)
It is also possible to remove the city names with a slight modification to the code.
# Map with no labels zoom of 6
leaflet() %>%
addProviderTiles("CartoDB.PositronNoLabels") %>%
setView(lng = -99.9018, lat = 31.9686, zoom = 6)
We change the map to one that states “PositronNoLabels” which removes the city and state names.
Predefined Limits
In this example, we will use several options to prevent the map from moving beyond a certain area and also limit how far you can zoom out. First, we use the options argument and set the leafletOptions() to a minimum zoom of 12, which means you cannot zoom out beyond that; we also allow dragging. Next, we pick our map using addProvidersTiles(). After this, we use the setView() function to set the location and zoom. Lastly, we use the setMaxBounds() function to set the location with a plus or minus of .05. Below is the code, followed by a picture of the map.
#stop map from moving beyond preset range
leaflet(options = leafletOptions(
# Set minZoom and dragging
minZoom = 12, dragging = T)) %>%
addProviderTiles("CartoDB") %>%
# Set default zoom level
setView(lng = -96.8, lat = 32.78, zoom = 14) %>%
# Set max bounds of map
setMaxBounds(lng1 = -96.8 + .05,
lat1 = 32.78 + .05,
lng2 = -96.8 - .05,
lat2 = 32.78 - .05)
The map is set over the Dallas area.
Below is the interactive feature of this same map. Notice how when I drag it too far, it automatically pulls me back. This forces the map to always be within a certain area.
Conclusion
The leaflet package provides unique ways to develop interactive maps. As we continue this journey, we will learn of several powerful tools associated with this package.
