互联网地图学 — ex 2

Jianghao Wang

2017-12-10

1 R + leaflet 互联网制图

1.1 基本用法

  1. 通过 leaflet() 初始化一个地图.
  2. 利用以下函数 (e.g. addTiles, addMarkers, addPolygons) 来添加图层.
  3. 重复第二步完成你想要的设置.
  4. 输出地图.

一个简单的例子:

library(leaflet)
# library(magrittr)

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=116.67498, lat=40.40652, popup="The University of Chinese Academy of Sciences")
m  # Print the map

如果你对R中的管道操作(%>%)不熟悉,可以采用以下方式:

m <- leaflet()
m <- addTiles(m)
m <- addMarkers(m, lng=116.67498, lat=40.40652, popup="The University of Chinese Academy of Sciences")
m

leaflet中可以接受的输出数据包括以下几种:

  • From base R:

  • From the maps package:
    • the data frame from returned from map()

1.2 数据输入

第一种:输入数据为经纬度坐标

  • lng/lat matrix
  • data frame with lng/lat columns
m <- leaflet() %>% addTiles()
df <- data.frame(
  lat = rnorm(100),
  lng = rnorm(100),
  size = runif(100, 5, 20),
  color = sample(colors(), 100)
)
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

第二种:空间数据格式

sp package:

  • SpatialPoints[DataFrame]
  • Line/Lines
  • SpatialLines[DataFrame]
  • Polygon/Polygons
  • SpatialPolygons[DataFrame]

第三种:maps包中的数据

maps package:

  • the data frame from returned from map()
# install.packages("maps")
library(maps)
mapStates = map("state", fill = TRUE, plot = FALSE)
leaflet(data = mapStates) %>% addTiles() %>%
  addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE)