You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:R语言实现巴黎Velib实时单车数据地图循环生成

Solution: Automate Velib Map Generation & Save with Timestamps

Hey David, let's work through this together! The key here is to wrap your map-making logic into a reusable function, then pair it with a loop that handles timing and unique file naming. Here's a step-by-step implementation:

1. Prep: Load Required Packages

First, make sure you have all the necessary libraries installed and loaded:

install.packages(c("dplyr", "leaflet", "htmlwidgets", "tidyr"))
library(dplyr)
library(leaflet)
library(htmlwidgets)
library(tidyr)

2. Wrap Map Logic into a Function

This function will handle data fetching, cleaning, map creation, and saving in one go. We'll add a timestamp to the filename so each map gets a unique name:

generate_velib_map <- function() {
  # Fetch and clean data
  sta.Paris <- read.csv(
    url("https://opendata.paris.fr/explore/dataset/velib-disponibilite-en-temps-reel/download/?format=csv&timezone=Europe/Berlin&use_labels_for_header=true"),
    sep=";"
  )
  
  sta.Paris2 <- sta.Paris %>%
    separate(Coordonnées.géographiques, into=c("lat","lon"), sep=",") %>%
    mutate(lat=as.numeric(lat), lon=as.numeric(lon)) %>%
    select(-15) %>% # Remove the original coordinate column
    na.omit() %>%
    mutate(
      velorange = cut(
        Nombre.total.vélos.disponibles,
        breaks = c(0,5,10,15,20,25,100),
        right=F,
        labels = c("Tres peu [0-5)", "Peu [5-10)","Moyen [10-15)","Assez [15-20)","Beaucoup [20-25)", "Enormement [25-100)")
      )
    )
  
  # Create color palette and map
  pal <- colorFactor(
    palette = c("azure2","yellow","orange","red","red4","black"),
    domain = sta.Paris2$velorange
  )
  
  map.velib1 <- leaflet(data = sta.Paris2) %>%
    addTiles(urlTemplate = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png") %>%
    addCircleMarkers(
      ~lon, ~lat,
      color = ~pal(velorange),
      radius=3,
      stroke = FALSE,
      fillOpacity = 0.7,
      popup = ~sprintf("<b> Vélos dispos: %s</b>", as.character(Nombre.total.vélos.disponibles))
    )
  
  # Save map with timestamped filename (e.g., velib_map_20240520_143000.html)
  timestamp <- format(Sys.time(), "%Y%m%d_%H%M%S")
  saveWidget(map.velib1, file = paste0("velib_map_", timestamp, ".html"))
  
  # Optional: Print status update to track progress
  cat(sprintf("Map saved successfully at %s\n", timestamp))
}

3. Implement the Loop

Now we'll create a loop that runs this function at your desired interval. Two flexible options:

Option A: Run a Fixed Number of Times (e.g., 24 hourly updates)

# Run once per hour for 24 hours
for(i in 1:24) {
  generate_velib_map()
  # Wait 1 hour (3600 seconds) before the next run
  Sys.sleep(3600)
}

Option B: Run Until a Specific End Time (e.g., end of the day)

# Set your target end time (adjust the date/time to your needs)
end_time <- as.POSIXct("2024-05-20 23:59:59", tz = "Europe/Paris")

while(Sys.time() < end_time) {
  generate_velib_map()
  # Wait 1 hour before the next iteration
  Sys.sleep(3600)
}

4. Key Tips to Avoid Common Issues

  • Rate Limiting: Don't set the interval too short (e.g., <10 minutes) — the OpenData Paris API might block frequent requests. Stick to 30+ minute intervals for safety.
  • Error Handling: Add tryCatch inside the function to handle network glitches, so a temporary failure doesn't break the entire loop:
    generate_velib_map <- function() {
      tryCatch({
        # All existing function code here
      }, error = function(e) {
        cat(sprintf("Error at %s: %s\n", format(Sys.time()), e$message))
      })
    }
    
  • File Organization: By default, maps save to your current working directory. Use getwd() to check your location, or add a folder path to saveWidget (e.g., file = paste0("./velib_daily_maps/velib_map_", timestamp, ".html")) — just make sure the folder exists first!

内容的提问来源于stack exchange,提问作者David Potrel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:43:13