Introduction

The Sacramento crime January 2006 file contains 7,584 crime records, as made available by the Sacramento Police Department. For this project, data downloaded from all forces for January 2006 for the whole city of Sacramento is used.

The used data is from: https://support.spatialkey.com/spatialkey-sample-csv-data/

Preparing your data

setwd("/Users/Kristianto_97/Desktop/Important Documents/School/R")
data <- read.csv("Sacramento 2006 Crime.csv")

Mapping your data in clusters

When clicking on clusters, you’ll notice blue markers that are there to call out points on the map. These are expressed in latitude and longitude coordinates of the data. To see these markers, you can zoom in to each cluster by clicking on it until the clusters separate.

To make clusters of markers, use addMarkers(clusterOptions = markerCLusterOptions()). The crimedescr is also added as a popup for each marker to identify what type of crime was committed

library(leaflet)
my_map <- data %>% 
  leaflet() %>% 
  addTiles() %>% 
  addMarkers(popup = data$crimedescr, clusterOptions=markerClusterOptions())
## Assuming "longitude" and "latitude" are longitude and latitude, respectively
my_map

Customizing your markers

The blue markers that leaflet comes packaged with may not be enough depending on what you’re mapping. Fortunately, you can make your own markers from .png files using the function makeIcon! To do this, pick out the URL icon, and your desired width, height and anchors.

Click on any cluster in the second map until you can see the criminal icon.

Image from: https://www.flaticon.com/free-icon/burglar_190640

crimeIcon <- makeIcon(
  iconUrl = "https://cdn4.iconfinder.com/data/icons/people-of-crime-and-protection/512/People_Crime_Protection_burglar_man-512.png",
  iconWidth = 31*215/230, iconHeight = 31,
  iconAnchorX = 31*215/230/2, iconAnchorY = 16
)
my_map <- data %>% 
  leaflet() %>% 
  addTiles() %>% 
  addMarkers(icon = crimeIcon, popup = data$crimedescr, clusterOptions=markerClusterOptions())
## Assuming "longitude" and "latitude" are longitude and latitude, respectively
my_map

Conclusion

Leaflet is one of the most popular Javascript libraries for creating interactive maps. And with the leaflet R package, users are allowed to create their own leaflet maps without needing to know any Javascript!