Quick code for creating a map. Note that the code/text are taken in the vast majority from other websites.

Leaflet package

Based on: - https://rstudio.github.io/leaflet/

You create a Leaflet map with these basic steps:

library(leaflet)
## Warning: package 'leaflet' was built under R version 3.5.3
library(maps) # package to have access to certain maps
## Warning: package 'maps' was built under R version 3.5.3
# basic example
m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")

m
# m <- leaflet()
# m <- addTiles(m)
# m <- addMarkers(m, lng=174.768, lat=-36.852, popup="The birthplace of R")

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

leaflet(df) %>%
  addTiles() %>%
  addCircles()
m = leaflet() %>% addTiles()
df = data.frame(
  lat = rnorm(100),
  lng = rnorm(100),
  size = runif(100, 5, 20),
  color = sample(colors(), 100)
)

head(df)
##            lat         lng      size        color
## 1  0.804580853 -0.71603807  5.099853 lightyellow4
## 2 -0.009570756 -0.05664122  9.507854       grey37
## 3 -1.011495564  0.95215261 12.675714       sienna
## 4  1.098541773  0.28321435  8.006455   slategray2
## 5 -0.489707877  0.75033444 19.941756      bisque3
## 6 -0.187906985 -0.47494185 10.007748       grey22
m = leaflet(df) %>% addTiles()
m %>% addCircleMarkers(radius = ~size, color = ~color, fill = FALSE)
## Assuming "lng" and "lat" are longitude and latitude, respectively
m %>% addCircleMarkers(radius = runif(100, 4, 10), color = c('red'))
## Assuming "lng" and "lat" are longitude and latitude, respectively

Using basemaps

By default, OpenStreetMap is used. Other are available, use names(providers) to check

m <- leaflet() %>% setView(lat = 35.683489, lng = 139.747840, zoom = 12)
m %>% addTiles()
m %>% addProviderTiles(providers$Stamen.Toner)
m %>% addProviderTiles(providers$CartoDB.Positron)
m %>% addProviderTiles(providers$Esri.NatGeoWorldMap)

Markers

Use markers to call out points on the map. Marker locations are expressed in latitude/longitude coordinates, and can either appear as icons or as circles.

To use:

  • Two-column numeric matrices (first column is longitude, second is latitude)
  • Data frame with latitude and logitude columns. You can explicitly tell the marker function which columns contain the coordinate data (e.g. addMarkers(lng = ~Longitude, lat = ~Latitude)), or let the function look for columns named lat/latitude and lon/lng/long/longitude (case insensitive).
  • Simply provide numeric vectors as lng and lat argument
data(quakes)

head(quakes)
##      lat   long depth mag stations
## 1 -20.42 181.62   562 4.8       41
## 2 -20.62 181.03   650 4.2       15
## 3 -26.00 184.10    42 5.4       43
## 4 -17.97 181.66   626 4.1       19
## 5 -20.42 181.96   649 4.0       11
## 6 -19.68 184.31   195 4.0       12
# Show first 20 rows from the `quakes` dataset
leaflet(data = quakes[1:20,]) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.character(mag), label = ~as.character(mag))

Customizing Marker Icons

You can provide custom markers in one of several ways, depending on the scenario. For each of these ways, the icon can be provided as either a URL or as a file path.

For the simple case of applying a single icon to a set of markers, use makeIcon().

Example:

  • Make a list of icons. We’ll index into it based on name. oceanIcons <- iconList( ship = makeIcon(“ferry-18.png”, “ferry-18@2x.png”, 18, 18), pirate = makeIcon(“danger-24.png”, “danger-24@2x.png”, 24, 24) )

  • Some fake data df <- sp::SpatialPointsDataFrame( cbind( (runif(20) - .5) * 10 - 90.620130, # lng (runif(20) - .5) * 3.8 + 25.638077 # lat ), data.frame(type = factor( ifelse(runif(20) > 0.75, “pirate”, “ship”), c(“ship”, “pirate”) )) )

leaflet(df) %>% addTiles() %>% # Select from oceanIcons based on df$type addMarkers(icon = ~oceanIcons[type])

# first 20 quakes
df.20 <- quakes[1:20,]

getColor <- function(quakes) {
  sapply(quakes$mag, function(mag) {
  if(mag <= 4) {
    "green"
  } else if(mag <= 5) {
    "orange"
  } else {
    "red"
  } })
}

icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = getColor(df.20)
)

leaflet(df.20) %>% addTiles() %>%
  addAwesomeMarkers(~long, ~lat, icon=icons, label=~as.character(mag))

“The addAwesomeMarkers() function is similar to addMarkers() function but additionally allows you to specify custom colors for the markers as well as icons from the Font Awesome, Bootstrap Glyphicons, and Ion icons icon libraries.

Similar to the makeIcon, icons, and iconList functions described above, you have makeAwesomeIcon, awesomeIcons and awesomeIconList functions, which enable you to add awesome icons.

The library argument has to be one of ‘ion’, ‘fa’, or ‘glyphicon’. The icon argument needs to be the name of any valid icon supported by the the respective library (w/o the prefix of the library name)."

icons <- awesomeIcons(
  icon = 'book',
  iconColor = '#ffffff',
  library = 'fa',
  markerColor = getColor(df.20)
)

leaflet(df.20) %>% addTiles() %>%
  addAwesomeMarkers(~long, ~lat, icon=icons, label=~as.character(mag))

Following code found on https://www.worldfullofdata.com/how-to-start-working-leaflet-r/

highlights_sydney <- data.frame(highlight = c("Sydney Harbour Bridge", "Sydney Tower Eye", "Darling Harbour", "Sydney Opera House", "Circular Quay", "Paddy's Haymarket", "China Town", "Taronga Zoo"),
                                lng = c(151.2102386, 151.206566, 151.198706, 151.2148, 151.2021077, 151.2035053, 151.2034301, 151.2331529),
                                lat = c(-33.8523063, -33.870451, -33.87488, -33.8567844, -33.8617552, -33.8793335, -33.8790999, -33.8430217)
)

# Plot map of the world
map <- leaflet() %>%
  addTiles()

map <- map %>%
  setView(151.2293, -33.84, zoom = 12)

map <- map %>% 
  addMarkers(data = highlights_sydney, lng = ~lng, lat = ~lat, popup = ~highlight, group = "markers")
map
# Add custom markers
highlights_sydney$icon <- c("camera", "camera", "ship", "camera", "ship", "shopping-cart", "shopping-cart", "ios-paw")
highlights_sydney$library <- c("glyphicon", "glyphicon", "fa", "glyphicon", "fa", "fa", "fa", "ion")

icons <- awesomeIcons(
  icon = highlights_sydney$icon,
  library = highlights_sydney$library,
  iconColor = "#ffffff",
  markerColor = "blue"
)

map <- map %>%
  addAwesomeMarkers(data = highlights_sydney, lng = ~lng, lat = ~lat, popup = ~highlight, icon = icons, group = "custom marker")
map

Marker Clusters

When zoom in, zoom out, it removes/adds the cluster! You can block the zoom (of the cluster) with markerClusterOptions(freezeAtZoom = 5) argument so that the number of clusters stay the same

leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions()
)
## Assuming "long" and "lat" are longitude and latitude, respectively
#  zoom frozen

leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions(freezeAtZoom = 5)
)
## Assuming "long" and "lat" are longitude and latitude, respectively

Test on Kaggle dataset

Source: https://www.kaggle.com/koki25ando/hostel-world-dataset/downloads/hostel-world-dataset.zip/6

library(readr)
## Warning: package 'readr' was built under R version 3.5.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 3.5.3
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
ds <- read_csv("C:/Users/Ndee/Documents/R/own_project/190525_mapping/Hostel.csv")
## Warning: Missing column names filled in: 'X1' [1]
## Parsed with column specification:
## cols(
##   X1 = col_double(),
##   hostel.name = col_character(),
##   City = col_character(),
##   price.from = col_double(),
##   Distance = col_character(),
##   summary.score = col_double(),
##   rating.band = col_character(),
##   atmosphere = col_double(),
##   cleanliness = col_double(),
##   facilities = col_double(),
##   location.y = col_double(),
##   security = col_double(),
##   staff = col_double(),
##   valueformoney = col_double(),
##   lon = col_double(),
##   lat = col_double()
## )
ds <- dplyr::filter(ds, lat != is.na(ds$lat)) 


m <- leaflet() %>% setView(lat = 35.682868, lng = 138.251761, zoom = 6)
m <- m %>% addTiles()

#cluster  
m %>% addMarkers(data = ds, lng = ~lon, lat = ~lat,
                   popup = ~as.character(hostel.name), 
                   label = ~as.character(hostel.name),
                   clusterOptions = markerClusterOptions())
# add possibility to capture distance
m %>% addMarkers(data = ds, lng = ~lon, lat = ~lat,
                 popup = ~as.character(hostel.name), 
                 label = ~as.character(hostel.name)) %>%
                 
#                 fitBounds(13.76134, 52.675499, 13.0884, 52.33812) %>%
                   addMeasure(
                     position = "bottomleft",
                     primaryLengthUnit = "meters",
                     primaryAreaUnit = "sqmeters",
                     activeColor = "#3D535D",
                     completedColor = "#7D4479")
# add a mini map
m %>% addMarkers(data = ds, lng = ~lon, lat = ~lat,
                 popup = ~as.character(hostel.name), 
                 label = ~as.character(hostel.name)) %>%
  addProviderTiles(providers$Esri.WorldStreetMap) %>%
  addMiniMap(
    tiles = providers$Esri.WorldStreetMap,
    toggleDisplay = TRUE)
# Testing icons
icons <- awesomeIcons(
  icon = "hotel",
  library = "fa",
  iconColor = "#ffffff",
  markerColor = "blue"
)

map <- m %>%
  addAwesomeMarkers(data = ds, lng = ~lon, lat = ~lat,
                 popup = ~as.character(hostel.name), 
                 label = ~as.character(hostel.name), 
                 icon = icons, group = "custom marker")
map