Leaflet is one of the most popular open source java scrip libraries for interactive maps. It’s being used in many places ranging from news papers to github to flickr. This R package makes it easy to integrate and control Leaflet maps in R.
We can create a basic leaflet map widget with the help of leaflet() function and adding default openstreet map Tile to it. The main input the Tile widget is latitude and longitude geo coordinates. We can get the geocode coordinates of any place by using ggmap package. Here is a simple basic usage which displays my home town. Simply replace the string argument to the geocode() function to display map of your home town.
library(leaflet)
library(ggmap)
library(maps)
library(ggplot2)
ll<-geocode("Vijayawada") ## plugin your home town.
ll %>% leaflet() %>%
addTiles() %>% ## add default OpenStreetMap map tiles
addMarkers(popup="My birthplace") # print the map
The markers widget in the leaflet allow us to call out points on the map. Marker locations are expressed in latitude/longitude coordinates. The markers can either appear as icons or as circles.
I’d like to mark some of the places that I visited and/or I lived in the United States. Here are the steps to show them on the map.
## collect list of cities
cities<-c("Chicago","New York","Boston","Atlanta","Destin","Orlando","San Francisco",
"San jose","Niagara Falls NY","Bloominton IL","Pittsburgh PA","Edison NJ","Memphis","Kansas City", "Hamilton ON","Ashville TN","Chattanooga TN",
"Detroit","Saint Paul MN","Louisville","Raleigh","Columbia SC","Washington DC","Branson",
"St Louis","Gatlinburgh TN","Charlotte","Clearwater FL","Charleston NC","Green Bay WI",
"Madison WI","Davenport","Flint","Holland MI","Aurora IL","Peoria IL","Springfield IL",
"Nashville TN","Dayton OH","Wilmington NC","Richmond VA","Las Vegas","Poughkeepsie NY",
"Atlantic City NJ","Daytona Beach","Myrtle Beach SC","Cape Canaveral FL","Elgin IL")
citygeo<-geocode(cities) ## get lat/long coordinates.
Note that the warning = FALSE parameter was added to the code chunk to prevent the R code display its output while generating lat/long coordinates.
Now, lets add circle markers along with popup and label text to show the locations on the map. We’ll also cluster the markers using cluster options to make it more fun.
# Add markers, popups and label them. Start with my current location.
citygeo %>% leaflet() %>% setView(lng = -88.93638, lat= 40.52656,zoom = 8) %>% addTiles %>%
addCircleMarkers(popup=cities,label=cities,clusterOptions=markerClusterOptions()) %>%
addProviderTiles(providers$OpenStreetMap)
By combining leaflet and Shiny, we can create powerful embed maps in knitr/R Markdown documents and Shiny apps.
The Leaflet package includes powerful and convenient features for integrating with Shiny applications.