Xianping Li A learner

R package - leaflet

Interactive map

It will be wonderful to draw interactive maps.

In some situations we can use the package leaflet (which is based on the open source JavaScript library leaflet) in R to do our visualizational tasks. There are some detailed tutorials about this package. This is the R package documentation maintained by RStudio, this is the official site of the JavaScript library leaflet, and this website provides many other useful widgets in R except leaflet.

Example

I will use a gpx file exported from my Garmin device as an example (a circular track in Olympic Forest Park, Beijing) to demonstrate some practical functions in leaflet with R.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
library(rgdal)
library(leaflet)

# Read the file
track <- readOGR("garmin.gpx","tracks")

# Coordinates, start point and end point
coord <- as.data.frame(coordinates(track))
names(coord) <- c("long","lat")

startP <- coord[1,]
endP <- coord[nrow(coord),]

points <- data.frame(rbind(startP,endP), 
    type=c("Start Point","End Point"))

# Mapping
leaflet() %>%
    addTiles(options=tileOptions( # add OpenStreetMap tiles
        minZoom=10,
        maxZoom=15)) %>% 
    addPolylines(data=track, # add track (SpatialLinesDataFrame)
        color="blue",
        options=pathOptions(
            clickable=FALSE)) %>%
    addMarkers(data=points, # add markers with popups
        lng=~long,
        lat=~lat,
        popup=~type,
        options=markerOptions(
            clickable=TRUE
            ))