Introduction

In this report, we call the taxi-availability real-time API, and visualize the current locations of all available taxis on a leaflet map. The API returns latitude and longitude data of all available taxis at a given timing, which you can define by setting the date_time parameter.

In order to call the API, you will have to apply for an API-Key, by creating an account here. Lastly, in order to obtain the most current data, we leave the date_time parameter blank.

Import key libraries, and set working directory

setwd("~/")
library(httr); library(jsonlite)
library(ggplot2); library(leaflet)
library(magrittr)

The API Key has been set to the variable api_key.

Let’s begin by making a call to the taxi-availability API.

Calling the API from data.gov.sg

url <- "https://api.data.gov.sg/v1/transport/taxi-availability"
r <- GET(url = url, add_headers("api-key" = api_key))
r$status_code
## [1] 200

Since the status code is 200, we can begin to obtain the latitude and longitude data from the API.

We proceed to store the obtained lng and lat data into a dataframe

raw_data <- content(r, "parsed")

# Create a function to store latitude and longitude data
lng <- sapply(raw_data$features[[1]]$geometry$coordinates, function(x) return(x[[1]][1]))
lat <- sapply(raw_data$features[[1]]$geometry$coordinates, function(x) return(x[[2]][1]))
df <- data.frame(lng, lat)

Let’s take a quick look at the data frame before plotting the data!

head(df)
##        lng      lat
## 1 103.6214 1.277544
## 2 103.6228 1.286960
## 3 103.6235 1.299340
## 4 103.6238 1.285610
## 5 103.6238 1.281760
## 6 103.6258 1.302980

Plotting

Now that we have stored the longitude and latitude data into a dataframe df, we can begin plotting!

df %>%
leaflet() %>%
addTiles() %>%
addCircleMarkers(weight = 1, radius = 10, clusterOptions = 
markerClusterOptions(iconCreateFunction=JS("function (cluster) {    
    var childCount = cluster.getChildCount(); 
    var c = ' marker-cluster-';  
    if (childCount < 10) {  
      c += 'large';  
    } else if (childCount < 50) {  
      c += 'medium';  
    } else { 
      c += 'small';  
    }    
    return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });

  }"))
)