直接上代碼,以下:html
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
詳見:上海地鐵git