In [9]:
library(rCharts)
options(rcharts.mode = 'ipynb')
library(httr); library(RColorBrewer)
In [2]:
L1 <- Leaflet$new()
L1$tileLayer(provider = 'Stamen.TonerLite')
L1$setView(c(40.73029, -73.99076), 13)
L1$set(width = 1200, height = 600)
L1
Out[2]:

In [5]:
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]]
Out[5]:
$bikes
[1] 26

$name
[1] "72 - W 52 St & 11 Ave"

$idx
[1] 0

$lat
[1] 40767272

$timestamp
[1] "2014-05-08T19:34:56.383Z"

$lng
[1] -73993928

$id
[1] 0

$free
[1] 13

$number
[1] 72

$longitude
[1] -73.99393

$latitude
[1] 40.76727

In [7]:
L1$geoJson(toGeoJSON(bike))
L1
Out[7]:

In [11]:
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")]
Out[11]:
$name
[1] "72 - W 52 St & 11 Ave"

$number
[1] 72

$free
[1] 13

$fillColor
[1] #A6D96A
Levels: #D7191C #FDAE61 #FFFFBF #A6D96A #1A9641

In [14]:
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)
72 - W 52 St & 11 Ave
Free Docks: 13
Available Bikes: 26
Retrieved At: 2014-05-08T19:34:56.383Z
In [15]:
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
Out[15]: