library(rCharts)
options(rcharts.mode = 'ipynb')
library(httr); library(RColorBrewer)
L1 <- Leaflet$new()
L1$tileLayer(provider = 'Stamen.TonerLite')
L1$setView(c(40.73029, -73.99076), 13)
L1$set(width = 1200, height = 600)
L1
network <- 'citibikenyc'
url = sprintf('//api.citybik.es/%s.json', network)
bike = content(GET(url))
bike = lapply(bike, function(station){within(station, {
latitude = as.numeric(lat)/10^6
longitude = as.numeric(lng)/10^6
})
})
bike[[1]]
L1$geoJson(toGeoJSON(bike))
L1
bike <- lapply(bike, function(station){within(station, {
fillColor = cut(
as.numeric(bikes)/(as.numeric(bikes)+as.numeric(free)),
breaks = c(0, 0.20, 0.40, 0.60, 0.80, 1),
labels = brewer.pal(5, 'RdYlGn'),
include.lowest = TRUE
)})
})
bike[[1]][c("name", "number", "free", "fillColor")]
popup_tpl = "
<b> {{name}} </b><br>
<b>Free Docks: </b> {{free}} <br>
<b>Available Bikes:</b> {{bikes}}<br>
<b>Retrieved At:</b> {{timestamp}}
"
bike <- lapply(bike, function(station){within(station, {
popup = iconv(
whisker::whisker.render(popup_tpl),
from = 'latin1', to = 'UTF-8')})
})
IRdisplay::display_html(bike[[1]]$popup)
L1$geoJson(toGeoJSON(bike),
onEachFeature = '#! function(feature, layer){
layer.bindPopup(feature.properties.popup)
} !#',
pointToLayer = "#! function(feature, latlng){
return L.circleMarker(latlng, {
radius: 4,
fillColor: feature.properties.fillColor || 'red',
color: '#000',
weight: 1,
fillOpacity: 0.8
})
} !#"
)
L1