基于运输时间的热图/等值线(反向等时线)

2022-09-02 13:50:38

注意:需要 中的解决方案(如有必要)。

我正在尝试根据运输时间绘制轮廓。为了更清楚起见,我想将具有相似行程时间(假设10分钟间隔)的点聚类到特定点(目的地),并将它们映射为等值线或热图。

现在,我唯一的想法是使用R包gmapsdistance来查找不同起源的旅行时间,然后将它们聚类并在地图上绘制。但是,正如您所知道的,这绝不是一个强大的解决方案。

GIS社区的这个线程和python的这个线程说明了类似的问题,但是对于特定时间内到达的目的地的起点。我想找到可以在一定时间内到达目的地的起点。

现在,下面的代码显示了我的基本想法(使用R):

library(gmapsdistance)

set.api.key("YOUR.API.KEY") 

mdestination <- "40.7+-73"
morigin1 <- "40.6+-74.2"
morigin2 <- "40+-74"

gmapsdistance(origin = morigin1,
              destination = mdestination,
              mode = "transit")

gmapsdistance(origin = morigin2,
              destination = mdestination,
              mode = "transit")

这张地图也可能有助于理解这个问题:

1

使用这个答案,我可以得到我可以从原点去的点,但我需要反转它,找到旅行时间等于一定时间到达目的地的点;

library(httr)
library(googleway)
library(jsonlite)
appId <- "TravelTime_APP_ID"
apiKey <- "TravelTime_API_KEY"
mapKey <- "GOOGLE_MAPS_API_KEY"

location <- c(40, -73)
CommuteTime <- (5 / 6) * 60 * 60

url <- "http://api.traveltimeapp.com/v4/time-map"

requestBody <- paste0('{ 
                      "departure_searches" : [ 
                      {"id" : "test", 
                      "coords": {"lat":', location[1], ', "lng":', location[2],' }, 
                      "transportation" : {"type" : "driving"} ,
                      "travel_time" : ', CommuteTime, ',
                      "departure_time" : "2017-05-03T07:20:00z"
                      } 
                      ] 
                      }')

res <- httr::POST(url = url,
                  httr::add_headers('Content-Type' = 'application/json'),
                  httr::add_headers('Accept' = 'application/json'),
                  httr::add_headers('X-Application-Id' = appId),
                  httr::add_headers('X-Api-Key' = apiKey),
                  body = requestBody,
                  encode = "json")

res <- jsonlite::fromJSON(as.character(res))

pl <- lapply(res$results$shapes[[1]]$shell, function(x){
  googleway::encode_pl(lat = x[['lat']], lon = x[['lng']])
})
df <- data.frame(polyline = unlist(pl))

df_marker <- data.frame(lat = location[1], lon = location[2])

google_map(key = mapKey) %>%
  add_markers(data = df_marker) %>%
  add_polylines(data = df, polyline = "polyline")

enter image description here



此外,旅行时间地图平台的文档讨论了具有到达时间的多起源,这正是我想做的事情。但是我需要为公共交通和驾驶(对于通勤时间少于一小时的地方)都这样做,我认为由于公共交通很棘手(基于您靠近的车站),也许热图是比等值线更好的选择。


答案 1

这个答案是基于在(大致)同样远的点的网格之间获得一个起点-目的地矩阵。这是一个计算机密集型操作,不仅因为它需要大量的 API 调用来映射服务,还因为服务器必须为每个调用计算一个矩阵。所需调用数沿网格中的点数呈指数级增长。

为了解决这个问题,我建议您考虑在本地计算机上运行,或者在本地服务器上运行映射服务器。Project OSRM 提供了一个相对简单、免费且开源的解决方案,使您能够将 OpenStreetMap 服务器运行到 Linux docker 中(https://github.com/Project-OSRM/osrm-backend)。拥有自己的本地映射服务器将允许您根据需要进行任意数量的 API 调用。R的osrm包允许您与OpenStreetMaps的API进行交互,包括那些放置在本地服务器上的API。

library(raster) # Optional
library(sp)
library(ggmap)
library(tidyverse)
library(osrm)
devtools::install_github("cmartin/ggConvexHull") # Needed to quickly draw the contours
library(ggConvexHull)

我在布鲁塞尔(比利时)大都市周围创建了一个由96个大致相同距离的点组成的网格。该网格不考虑地球曲率,在城市距离水平上可以忽略不计。

为方便起见,我使用栅格包下载比利时的 ShapeFile 并提取布鲁塞尔市的节点。

  BE <- raster::getData("GADM", country = "BEL", level = 1)
  Bruxelles <- BE[BE$NAME_1 == "Bruxelles", ]

  df_grid <- makegrid(Bruxelles, cellsize = 0.02) %>% 
        SpatialPoints() %>%
        ## I convert the SpatialPoints object into a simple data.frame 
        as.data.frame() %>% 
        ## create a unique id for each point in the data.frame
        rownames_to_column() %>% 
        ## rename variables of the data.frame with more explanatory names.
        rename(id = rowname, lat = x2, lon = x1) 

 ## I point osrm.server to the OpenStreet docker running in my Linux machine. ... 
 ### ... Do not run this if you are getting your data from OpenStreet public servers.
 options(osrm.server = "http://127.0.0.1:5000/") 

 ## I obtain a list with distances (Origin Destination Matrix in ...
 ### ... minutes, origins and destinations)
 Distance_Tables <- osrmTable(loc = df_grid) 

 OD_Matrix <- Distance_Tables$durations %>% ## subset the previous list
                ## convert the Origin Destination Matrix into a tibble
                as_data_frame() %>%  
                rownames_to_column() %>% 
                ## make sure we have an id column for the OD tibble
                rename(origin_id = rowname) %>% 
                ## transform the tibble into long/tidy format
                gather(key = destination_id, value = distance_time, -origin_id) %>% 
                left_join(df_grid, by = c("origin_id" = "id")) %>% 
                ## set origin coordinates
                rename(origin_lon = lon, origin_lat = lat) %>% 
                left_join(df_grid, by = c("destination_id" = "id")) %>% 
                ## set destination coordinates
                rename(destination_lat = lat, destination_lon = lon) 

 ## Obtain a nice looking road map of Brussels
 Brux_map <- get_map(location = "bruxelles, belgique", 
                     zoom = 11, 
                     source = "google", 
                     maptype = "roadmap")

 ggmap(Brux_map) + 
   geom_point(aes(x = origin_lon, y = origin_lat), 
              data = OD_Matrix %>% 
                ## Here I selected point_id 42 as the desired target, ...
                ## ... just because it is not far from the City Center.
                filter(destination_id == 42), 
                size = 0.5) + 
   ## Draw a diamond around point_id 42                                      
   geom_point(aes(x = origin_lon, y = origin_lat), 
              data = OD_Matrix %>% 
                filter(destination_id == 42, origin_id == 42),
              shape = 5, size = 3) +  
   ## Countour marking a distance of up to 8 minutes
   geom_convexhull(alpha = 0.2, 
                   fill = "blue", 
                   colour = "blue",
                   data = OD_Matrix %>% 
                            filter(destination_id == 42, 
                            distance_time <= 8), 
                   aes(x = origin_lon, y = origin_lat)) + 
   ## Countour marking a distance of up to 16 minutes
   geom_convexhull(alpha = 0.2, 
                   fill = "red",
                   colour = "red",
                   data = OD_Matrix %>% 
                            filter(destination_id == 42, 
                                   distance_time <= 15), 
                   aes(x = origin_lon, y = origin_lat))

结果

蓝色等值线表示到市中心的距离,最长可达 8 分钟。红色等值线表示最长 15 分钟的距离。

enter image description here


答案 2

我想出了一种与进行大量API调用相比适用的方法。

这个想法是找到你可以在一定时间内到达的地方(看看这个线程)。可以通过将时间从早上更改为晚上来模拟交通。您最终将得到一个重叠的区域,您可以从两个地方到达。

然后,您可以使用Nicolas答案并映射该重叠区域内的一些点,并绘制您拥有的目的地的热图。这样,您将有更少的区域(点)来覆盖,因此您将进行更少的api调用(请记住为此使用适当的时间)。

下面,我试图证明我所说的这些是什么意思,并让你达到你可以使另一个答案中提到的网格,使你的估计更加健壮。

这将显示如何映射相交区域。

library(httr)
library(googleway)
library(jsonlite)
appId <- "Travel.Time.ID"
apiKey <- "Travel.Time.API"
mapKey <- "Google.Map.ID"

locationK <- c(40, -73) #K
locationM <- c(40, -74) #M

CommuteTimeK <- (3 / 4) * 60 * 60
CommuteTimeM <- (0.55) * 60 * 60
url <- "http://api.traveltimeapp.com/v4/time-map"

requestBodyK <- paste0('{ 
                      "departure_searches" : [ 
                      {"id" : "test", 
                      "coords": {"lat":', locationK[1], ', "lng":', locationK[2],' }, 
                      "transportation" : {"type" : "public_transport"} ,
                      "travel_time" : ', CommuteTimeK, ',
                      "departure_time" : "2018-06-27T13:00:00z"
                      } 
                      ] 
                      }')


requestBodyM <- paste0('{ 
                      "departure_searches" : [ 
                      {"id" : "test", 
                      "coords": {"lat":', locationM[1], ', "lng":', locationM[2],' }, 
                      "transportation" : {"type" : "driving"} ,
                      "travel_time" : ', CommuteTimeM, ',
                      "departure_time" : "2018-06-27T13:00:00z"
                      } 
                      ] 
                      }')

resKi <- httr::POST(url = url,
                  httr::add_headers('Content-Type' = 'application/json'),
                  httr::add_headers('Accept' = 'application/json'),
                  httr::add_headers('X-Application-Id' = appId),
                  httr::add_headers('X-Api-Key' = apiKey),
                  body = requestBodyK,
                  encode = "json")


resMi <- httr::POST(url = url,
                   httr::add_headers('Content-Type' = 'application/json'),
                   httr::add_headers('Accept' = 'application/json'),
                   httr::add_headers('X-Application-Id' = appId),
                   httr::add_headers('X-Api-Key' = apiKey),
                   body = requestBodyM,
                   encode = "json")
resK <- jsonlite::fromJSON(as.character(resKi))
resM <- jsonlite::fromJSON(as.character(resMi))

plK <- lapply(resK$results$shapes[[1]]$shell, function(x){
  googleway::encode_pl(lat = x[['lat']], lon = x[['lng']])
})

plM <- lapply(resM$results$shapes[[1]]$shell, function(x){
  googleway::encode_pl(lat = x[['lat']], lon = x[['lng']])
})
dfK <- data.frame(polyline = unlist(plK))
dfM <- data.frame(polyline = unlist(plM))

df_markerK <- data.frame(lat = locationK[1], lon = locationK[2], colour = "#green")
df_markerM <- data.frame(lat = locationM[1], lon = locationM[2], colour = "#lavender")

iconK <- "red"
df_markerK$icon <- iconK

iconM <- "blue"
df_markerM$icon <- iconM


google_map(key = mapKey) %>%
  add_markers(data = df_markerK,
              lat = "lat", lon = "lon",colour = "icon",
              mouse_over = "K_K") %>%
  add_markers(data = df_markerM, 
              lat = "lat", lon = "lon", colour = "icon",
              mouse_over = "M_M") %>%
  add_polygons(data = dfM, polyline = "polyline", stroke_colour = '#461B7E',
               fill_colour = '#461B7E', fill_opacity = 0.6) %>% 
  add_polygons(data = dfK, polyline = "polyline", 
               stroke_colour = '#F70D1A',
               fill_colour = '#FF2400', fill_opacity = 0.4)

enter image description here

您可以像这样提取相交区域:

# install.packages(c("rgdal", "sp", "raster","rgeos","maptools"))
library(rgdal)
library(sp)
library(raster)
library(rgeos)
library(maptools)
Kdata <- resK$results$shapes[[1]]$shell
Mdata <- resM$results$shapes[[1]]$shell

xyfunc <- function(mydf) {
  xy <- mydf[,c(2,1)]
  return(xy)
}

spdf <- function(xy, mydf){
            sp::SpatialPointsDataFrame(
                coords = xy, data = mydf,
                proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))}

for (i in (1:length(Kdata))) {Kdata[[i]] <- xyfunc(Kdata[[i]])}
for (i in (1:length(Mdata))) {Mdata[[i]] <- xyfunc(Mdata[[i]])}

Kshp <- list(); for (i in (1:length(Kdata))) {Kshp[i] <- spdf(Kdata[[i]],Kdata[[i]])}

Mshp <- list(); for (i in (1:length(Mdata))) {Mshp[i] <- spdf(Mdata[[i]],Mdata[[i]])}

Kbind <- do.call(bind, Kshp) 
Mbind <- do.call(bind, Mshp) 
#plot(Kbind);plot(Mbind)


x <- intersect(Kbind,Mbind)
#plot(x)

xdf <- data.frame(x)
xdf$icon <- "https://i.stack.imgur.com/z7NnE.png"

google_map(key = mapKey, 
           location = c(mean(latmax,latmin), mean(lngmax,lngmin)), zoom = 8) %>% 
     add_markers(data = xdf, lat = "lat", lon = "lng", marker_icon = "icon")

这只是相交区域的一个示例。

enter image description here

现在,您可以从数据帧中获取坐标,并围绕这些点构建格网,以最终生成热图。为了尊重提出这个想法/答案的其他用户,我没有把它包括在我的脑海中,我只是参考它。xdf

尼古拉斯·委拉斯开兹 - 在(大致)等距离点的网格之间获取起点-目的地矩阵