互联网地图学 — ex 3

Jianghao Wang

2017-12-06

1 Mapping with leaflet + R

1.1 Markers

利用经纬度坐标来标记地图上的点。可以输入的类型包括

  • SpatialPoints or SpatialPointsDataFrame objects (from the sp package)
  • POINT, sfc_POINT, and sf objects (from the sf package); only X and Y dimensions will be considered
  • 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 arguments

一个简单的实例

library(leaflet)
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))

Marker Clusters

leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions()
)

1.2 Points

leaflet(quakes) %>% addTiles() %>% addCircleMarkers()
## Assuming 'long' and 'lat' are longitude and latitude, respectively

Or customize their color, radius, stroke, opacity, etc.

# Create a palette that maps factor levels to colors
pal <- colorFactor(c("navy", "red"), domain = c("ship", "pirate"))
quakes$type <-  factor(ifelse(runif(nrow(quakes)) > 0.75, "pirate", "ship"),c("ship", "pirate"))

leaflet(quakes) %>% addTiles() %>%
  addCircleMarkers(
    radius = ~ifelse(type == "ship", 6, 10),
    color = ~pal(type),
    stroke = FALSE, fillOpacity = 0.5
  )
aqi <- read.csv("data/aqi.csv")
pal <- colorQuantile("YlOrRd", NULL, n=5)
leaflet(aqi) %>% addTiles()%>% 
  addCircleMarkers(~lon, ~lat , popup=aqi$PM25,
                   radius = log2(aqi$PM25),
                   stroke = FALSE, fillOpacity = 0.8,
                   color= ~pal(AQI)) 

1.3 Lines

# install.packages("sf")
library(sf)

china <- read_sf("data/china.shp")

plot(china)

leaflet(data = china) %>%
    addTiles() %>%
    addPolylines()