In this post, we will learn how to set markers and adjust the zoom of interactive maps created with the leaflet package using R.
Load Packages
We begin by loading the only package of this example, which is the leaflet package.
library(leaflet)
Set Markers
Markers are small icons you can place on a map to indicate a specific location. In the code below, we set a marker to indicate Dallas’ area on the map.
leaflet() %>% addProviderTiles("CartoDB") %>% addMarkers(lng = -96.8, lat = 32.78) %>% #add marker setView(lng = -96.8, lat = 32.78, zoom = 12)

The leaflet() function calls create the map. The addProviderTiles() function is used to pick the type of map to display, which in this case is the CartoDB map. The new function in this example is the addMarkers() function, which is used to place the blue marker at the location specified. Lastly, the setView() function sets the location and zoom of the map.
Of course, it is possible to have more than one marker on a map. The example below places markers on different continents.
# Plot both Texas and Belgium locationsleaflet() %>% addProviderTiles("CartoDB") %>% addMarkers(lng = c(-96.8, 4.717863), lat = c(32.78, 50.88136))

One aspect that is confusing about setting multiple markers is that you must place all the longitude values together in one concatenate function and all the latitude values in a different concatenate function, as shown above.
Adding Popups
Pops add text to a marker when the mouse hovers over it. The code below is mostly the same as previously, except the pop-up value is set to display Dallas, TX, and Belgium in the two different markers. Also note that we saved our code in an object called “map.”
#Popups# Store leaflet hq map in an object called mapmap <- leaflet() %>% addProviderTiles("CartoDB") %>% addMarkers(lng = c(-96.8, 4.717863), lat = c(32.78, 50.88136), popup = c("Dallas, TX","Belgium"))#Print mapmap

It’s only possible to hover over one marker at a time, but if you run the code, you can confirm that the marker in Belgium also has a pop-up.
Clearing a Map
For our last trick, we will clear the map. To do this, we need to use the clearMarkers() function to clear any markers and the clearBounds() function to remove any zoom or boundaries we set. Below is the code.
#CLEAR MAP# Remove markers, reset bounds, and store the updated map in the m objectmap_clear <- map %>% clearMarkers() %>% clearBounds()# Print the cleared mapmap_clear

Now we can begin again with a clean slate.
Conclusion
With these tools, you can now identify specific locations on a map with markers, add text in pop-ups, and clear a map when necessary. Creating interactive maps is another great skill that can be used in various situations.

