Chapter 13 Bonus : Drawing a map using Leaflet

Mapping with Leaflet

Leaflet is one of the most popular open-source JavaScript libraries for interactive maps. It provides features like Interactive panning/zooming, Map tiles, Markers, Polygons, Lines, Popups, GeoJSON, creating maps right from the R console or RStudio. It also allows you to render spatial objects from the sp or sf packages, or data frames with latitude/longitude columns using map bounds and mouse events to drive Shiny logic, and display maps in non-spherical Mercator projections.

Please install leaflet package to use all function including by it.

install.packages("leaflet")
library(leaflet)

Basic Usage

You create a Leaflet map with these basic steps:

  1. Create a map widget by calling it leaflet().
  2. Add layers to the map by using layer functions (e.g. addTiles, addMarkers, addPolygons) to modify the map widget.
  3. Print the map widget to display it. Here?s a basic example:
library(leaflet)
## Warning: package 'leaflet' was built under R version 4.1.3
leaflet()
leaflet()%>%addTiles() # Add default OpenStreetMap map tiles
leaflet()%>%addTiles() %>%addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
leaflet()%>%setView(lng=174.768, lat=-36.852, zoom=20)%>%addTiles() 
#setwiew sets the center of the map view and the zoom level.

Adding Circle to your map

# add some circles to a map
df = data.frame(Lat = 1:10, Long = rnorm(10))
leaflet(df) %>% addCircles()

You can also explicitly specify the Lat and Long columns:

leaflet(df) %>% addCircles(lng = ~Long, lat = ~Lat)

4) Draw a map of a place with zoom 20 and lattitude and longitude values 39.925018, 32.836956 respectively .