1 Leaflet
Create interactive maps.
Note: You have to turn on your internet connection to see all maps.
1.1 Creating Map
Let’s create my first Leaflet MAP
Data comes from Open Street Map.
This is just a background layer. We can add more things to this. Let’s try those.
1.2 Add Marker to Map
library(leaflet)
my_map <- my_map %>%
addMarkers(lat = 7.8731, lng = 80.7718, popup = "Sri Lanka")
my_mapmy_map2 <- addMarkers(map = my_map2, lat = 37.0902, lng = 95.7129, popup = "United States of America")
my_map2Let’s try all these codes together.
my_place <- leaflet() %>%
addTiles() %>%
addMarkers(lat = 7.2549, lng = 80.5974, popup = "My University:)")
my_place1.2.1 Adding lots of markers :)
set.seed(1234) # 1234
df <- data.frame(lat = runif(20, min = 23.54, max = 58.21),
lng = runif(20, min = 39.42, max = 86.32))
head(df)## lat lng
## 1 27.48210 54.26912
## 2 45.11512 53.61632
## 3 44.66355 46.87926
## 4 45.15257 41.29581
## 5 53.38794 49.68170
## 6 45.73957 77.43707
1.2.2 Adding custom markers
# Custom icons
uopIcon <- makeIcon(iconUrl = "https://www.pdn.ac.lk/commonfiles/imgs/crest.png",
iconWidth = 31*215/230, iconHeight = 31,
iconAnchorX = 31*215/230/2, iconAnchorY = 16)
# Marker locations
df <- data.frame(lat = c(7.2589, 7.2538, 7.2640, 7.2621, 7.2704),
lng = c(80.5986, 80.5916, 80.5987, 80.5959, 80.6046))
# Custom popups
uopSite <- c(
"<a href='http://sci.pdn.ac.lk/'>Faculty of Science</a>",
"<a href='http://eng.pdn.ac.lk/'>Faculty of Engineering</a>",
"<a href='http://med.pdn.ac.lk/'>Faculty of Medicine</a>",
"<a href='http://agri.pdn.ac.lk/'>Faculty of Agriculture</a>",
"<a href='http://dental.pdn.ac.lk/'>Faculty of Dental Science</a>")
df %>%
leaflet() %>%
addTiles() %>%
addMarkers(icon = uopIcon, popup = uopSite)1.3 Mapping clusters
1.4 Circular Markers
1.5 Draw shapes on Map
1.5.1 Circles
df <- data.frame(name = c("Sci", "eFac", "Medi", "Agri", "Denta"),
pop = c(2000, 2300, 1250, 1700, 970),
lat = c(7.2589, 7.2538, 7.2640, 7.2621, 7.2704),
lng = c(80.5986, 80.5916, 80.5987, 80.5959, 80.6046))
# pop means population
df %>%
leaflet() %>%
addTiles() %>%
addCircles(weight = 10, radius = sqrt(df$pop) * 10) ## Assuming "lng" and "lat" are longitude and latitude, respectively
1.6 Adding Legends
df <- data.frame(lat = runif(20, min = 7.2589, max = 7.2704),
lng = runif(20, min = 80.5916, max = 80.6046),
col = sample(c("red", "blue", "green"), 20, replace = TRUE),
stringsAsFactors = FALSE)
df %>%
leaflet() %>%
addTiles() %>%
addCircleMarkers(color = df$col) %>%
addLegend(labels = LETTERS[1:3], colors = c("blue", "red", "green"))## Assuming "lng" and "lat" are longitude and latitude, respectively