使用Leaflet绘制上海地铁地图

library(leaflet)
library(data.table)
library(dplyr)
stations <- fread('https://raw.githubusercontent.com/jeevanyue/jeevanyue.github.io/master/data/stations.csv',encoding='UTF-8')

stations <- arrange(stations,line,line_id)
#地铁颜色,从上海地铁官网获取
lines_color <- data.frame("line"=c(1:13,16),"color"=c("#ED3229","#36B854","#FFD823","#320176","#823094","#CF047A","#F3560F","#008CC1","#91C5DB","#C7AFD3","#8C2222","#007a61","#ec91cc","#32D2CA"))

pal <- colorFactor(as.character(lines_color$color), domain = stations$line)

Shanghai <- leaflet() %>% 
  setView(lng = 121.468888888889, lat = 31.2358333333333, zoom = 10) %>% 
  addProviderTiles("CartoDB.Positron")

## 辅助函数绘制线路
draw_line_add <- function(l_no,line_s_id=NULL){
  line_color <- lines_color[lines_color$line==l_no,]$color
  line_data <- stations[stations$line==l_no,]
  if(is.null(line_s_id)){
  draw_lines <- Shanghai %>%
    addPolylines(lat=line_data$gps_lat,lng=line_data$gps_lon,color=line_color)
  }else{
    draw_lines <- Shanghai %>%
      addPolylines(lat=line_data$gps_lat[line_s_id],lng=line_data$gps_lon[line_s_id],color=line_color)
  }
  return(draw_lines)
}

for(l in unique(stations$line)){
  line_length <- nrow(stations[stations$line==l,])
  if(l==4){
    #由于4号线为环线,需将首尾相连
    Shanghai <- draw_line_add(l_no=l)
    Shanghai <- draw_line_add(l_no=l,line_s_id=c(1,line_length))
  }else if(l==10){
    #由于10号线在龙溪路站以后分为两条线路,需分两端绘制
    Shanghai <- draw_line_add(l_no=l,line_s_id=c(1:(line_length-3)))
    Shanghai <- draw_line_add(l_no=l,line_s_id=c(24,(line_length-2):line_length))
  }else if(l==11){
    #由于11号线在嘉定新城站以后分为两条线路,需分两端绘制
    Shanghai <- draw_line_add(l_no=l,line_s_id=c(1:(line_length-7)))
    Shanghai <- draw_line_add(l_no=l,line_s_id=c(28,(line_length-6):line_length))
  }else{
    Shanghai <- draw_line_add(l_no=l)
  }
}

stations_no <- nrow(stations)
for (i in 1:stations_no) {
  s <- stations$station[i]
  stations$lines[i] <- paste(stations[stations$station==s,]$line,sep="",collapse="/")
}
#添加地铁站名
Shanghai <- Shanghai %>%
  addCircleMarkers(stations$gps_lon, stations$gps_lat, popup =paste(stations$station,stations$lines,sep=","),color = pal(stations$line), radius=1.5) %>%
  addLegend(pal=pal,values = stations$line)
Shanghai



转载自:https://blog.csdn.net/u011596455/article/details/79431614

You may also like...

退出移动版