1. Plotting DataCamp HQ
We have been creating maps with a single layer: a base map. To plot data on our maps, we can add layers to the base map similar to how you add a layer in ggplot2.
2. Plotting a Point
One of the most common layers to add are location markers, which you can add by piping the result of addTiles() into the addMarkers() function. There are several options for supplying the data for your markers. We'll focus on two approaches: using numeric columns from a data frame and using numeric vectors with a length of 1. For example, if we plot DataCamp's New York headquarters by passing the coordinates to addMarkers() as numeric vectors with one element, our web map will plot a blue pin. You may have noticed that our map is zoomed in, but we didn't use the setView or fitBounds(). When you add markers to your map without setting the view, leaflet will automatically set the boundaries of the base map based on the markers that you're plotting. If you're plotting a single marker, leaflet will center the map on that marker. If you're plotting multiple markers, leaflet will set the bounds so that they're all visible.
3. Plotting Multiple Points
If you want to add multiple markers, we can use a data frame or a tibble to pass the coordinates to the addMarkers() function. For example, to plot both DataCamp’s New York and Belgium offices, we can use a tibble with the coordinates in our addMarkers() function call.
4. Plotting Multiple Points II
An alternate approach to mapping points from a data frame is to pipe the data. Then addMarkers() will search the columns names for names that are most likely your coordinates and the leaflet package will send you a message to let you know if a match was found.
5. Pop-ups
It is often helpful to provide users with information about the points we have mapped. A common way to do this is by adding pop-ups that will appear whenever a user clicks on a marker. We can add pop-ups by specifying the popup argument in the addMarkers() function. For example, we can have the text from the hq column appear whenever a marker is clicked.
6. Pop-ups II
For this example with just two markers it may be more useful to add pop-ups to the map without the markers. We can do this by replacing addMarkers() with the addPopups() function. If we had more than a few markers, this approach may be problematic.
7. Storing leaflet Maps as Objects
Once we have our map shaped up to our liking we can store it in R object. Similar to how you store ggplots as R objects, you can add and edit layers of a leaflet map once it's stored as an object. For example, we can store our base map with a particular view as an object called m. Then we can pipe m into the addMarkers() function to plot DataCamp's office on the map.
8. Let's practice!
Now it's your turn to create a leaflet object that plots DataCamp's headquarters!