Skip to content

Instantly share code, notes, and snippets.

@tslumley tslumley/wellybus.R
Last active Aug 13, 2018

Embed
What would you like to do?
Slowly accumulating map of Wellington buses (rate-limited to 1 route per 40sec)
library(tidyverse)
library(leaflet)
library(jsonlite)
library(ratelimitr)
library(htmlwidgets)
library(htmltools)
allroutes<-read_csv("~/Downloads/WLG-google-transit/routes.txt") %>% filter(route_type==3)
download_route<-limit_rate(
function(route) fromJSON(paste0("https://www.metlink.org.nz/api/v1/ServiceLocation/",route)),
rate(n=1,period=20) )
makeItReload<-function(htmlfile){
contents<-readLines(htmlfile)
writeLines(gsub("</body>","<script type=\"text/javascript\"> setTimeout(function() { window.location.reload();}, 90*1000);</script></body>",contents, fixed=TRUE), htmlfile)
}
allpos<-vector("list",nrow(allroutes))
names(allpos)<-allroutes$route_short_name
repeat({
for(route in allroutes$route_short_name){
cat(route," ")
if ((length(allpos[[route]])!=0) && (allpos[[route]]$h < as.POSIXlt(Sys.time())$hour-2))
allpos[[route]]<-list()
this_route<-tryCatch(download_route(route), error=function(e) NULL)
if (is.null(this_route)) next
if (!length(this_route$Services)) next
if (NROW(this_route$Services)==0) next
df<-this_route$Services %>%
select(Lat,Long, DelaySeconds, RecordedAtTime) %>%
separate(RecordedAtTime, into=c("y","mth","d","h","m","s","tz","tz2"),sep="[-:T+]") %>%
mutate(lateness=case_when(DelaySeconds< -180 ~"magenta",
DelaySeconds>= -180 & DelaySeconds<300~ "forestgreen",
DelaySeconds>=300 & DelaySeconds<600~"orange",
DelaySeconds>=600~"red")) %>%
mutate(popup=paste0(route,paste("<br/>",abs(round(DelaySeconds/60)),"mins", ifelse(DelaySeconds<0,"early", "late"),"at",h,":",m)))
allpos[[route]]<-df
m <- leaflet(bind_rows(allpos)) %>%
addProviderTiles("CartoDB.Positron") %>%
addCircleMarkers(~as.numeric(Long),~as.numeric(Lat),col=~lateness,popup=~popup) %>%
addLegend("bottomright",title=paste("Wellington buses (past hour or so)"),
colors=c("magenta","forestgreen","orange","red"),labels=c("Early", "On schedule","5-10 min late","10+ min late"))
saveWidget(widget=m,"/Volumes/tlum005/buses/wellybus.html",selfcontained=FALSE)
tryCatch(
makeItReload("/Volumes/tlum005/buses/wellybus.html"),
error=function(e) {cat("Didn't reload\n")}
)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.