【问题标题】:Mapping Bus Routes with Leaflet in R在 R 中使用 Leaflet 映射巴士路线
【发布时间】:2017-03-22 20:01:13
【问题描述】:

我最近发现了这个纽约市公交路线的形状文件shape file of NYC bus routes (zip file),我有兴趣使用 R 中的传单包进行绘图。

当我尝试这样做时,有些路线没有显示在地图上。我可以说它们丢失了,因为我覆盖了巴士站数据,有些与路线不相符。

当我阅读形状文件时,我注意到创建的空间线数据框有嵌套列表,我认为传单没有映射。

我需要做什么才能让传单读取这些缺失路线的坐标?下面是我用来生成缺少路线的地图的代码:

bus <- readOGR(dsn = path.expand("bus_route_shapefile"), layer = "bus_route_shapefile")
bus.pj <- spTransform(bus, CRS("+proj=longlat +datum=WGS84"))
bus.st <- readOGR(dsn = path.expand("bus_stop_shapefile"), layer = "bus_stop_shapefile")
bus.st.pj <- spTransform(bus.st, CRS("+proj=longlat +datum=WGS84"))

bus_map <- leaflet() %>%
  setView(lng = -73.932667, lat = 40.717266, zoom = 11) %>%
  addPolylines(data = bus.pj, color = "black", opacity = 1) %>%
  addCircles(data=bus.st.pj@data,~stop_lon, ~stop_lat, color = "red") %>%
  addTiles()
bus_map

【问题讨论】:

    标签: r mapping leaflet


    【解决方案1】:

    如果您不仅提供了 bus_routes 还提供了bus_stop (zip file),对您的帮助会更容易。您可以通过将bus.pj 转换为新的SpatialLinesxxx obj 来解决它,其中每个类Lines 只有一个类LineSLDF 下面的代码使得没有 bus.pj@data$trip_heads 因为未知。

    library(dplyr); library(sp); library(leaflet)
    
      ## resolve bus.pj@lines into list(Line.objs)   (Don't worry about warnings)
    Line_list <- lapply(bus.pj@lines, getLinesLinesSlot) %>% unlist()
    
           ## If you want just Lines infromation, finish with this line.
         SL <- sapply(1:length(Line_list), function(x) Lines(Line_list[[x]], ID = x)) %>% 
           SpatialLines()
    
      ## make new ids (originalID_nth)
    ori_id <- getSLLinesIDSlots(bus.pj)                         # get original ids
    LinLS <- sapply(bus.pj@lines, function(x) length(x@Lines))  # how many Line.obj does each Lines.obj has
    new_id <- sapply(1:length(LinLS), function(x) paste0(x, "_", seq.int(LinLS[[x]]))) %>% 
      unlist()
    
      ## make a new data.frame (only route_id)
    df <- data.frame(route_id = rep(bus.pj@data$route_id, times = LinLS))
    rownames(df) <- new_id
    
      ## integrate Line.objs, ids and a data.frame into SpatialLinesDataFrame.obj
    SLDF <- mapply(function(x, y) Lines(x, ID = y), x = Line_list, y = new_id) %>% 
      SpatialLines() %>% SpatialLinesDataFrame(data = df)
    
    
    leaflet() %>%
      setView(lng = -73.932667, lat = 40.717266, zoom = 11) %>%
      addPolylines(data = SLDF, color = "black", opacity = 1, weight = 1) %>% 
      addCircles(data=bus.st.pj@data,~stop_lon, ~stop_lat, color = "red", weight = 0.3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多