Plotting flight paths with googleway in R

To mark the release of version 2.0 of our R package googleway package on CRAN, we will be documenting some tricks and tips to help get started (or to help dig into some of the finer points). For our first example we are going to build a visualisation of airline flight paths, like this:



Getting started

To get started, here's an example web app showing flight paths by country. First we need to load googleway. To use this package you need a valid API KEY (follow instructions here to get a key) for the API you wish to use. Note that the same API key can be used for all the functions, but you need to register it with each API first.

map_key <- "your_api_key"

Next we source some data. We are using data from the project for airline routes and flight paths. This page is a great, open resource for flight data.

# get the data 
url <- ''
flights <- read.csv(url)

# add a unique id
flights$id <- seq_len(nrow(flights))

Building the plot

The googleway package contains helper functions encode_pl and decode_pl to convert coordinates to and from an encoded string. For more information about the format see the google documentation

To prepare for plotting we encode each flight path as a single polyline.

## encode the routes as polylines
lst <- lapply(unique(flights$id), function(x){
  lat = c(flights[flights["id"] == x, c("start_lat")], flights[flights["id"] == x, c("end_lat")])
  lon = c(flights[flights["id"] == x, c("start_lon")], flights[flights["id"] == x, c("end_lon")])
  data.frame(id = x, polyline = encode_pl(lat = lat, lon = lon))

flights <- merge(flights,, lst), by = "id")

With googleway we can also control the style of the map. You can use your own custom styles by using a service like the snazzymaps website or use one of our inbuilt styles. We are using the night style (because who doesn't like seeing a dark map with bright lines).

style <- map_styles()$night

We build up the map in layers, using %>% to pipe data from one command to the next. The following code establishes a base layer and then adds polylines to it by specifying the column name containing the encoded polylines. The mouse_over_group specifies which subset of lines to highlight on mouseover.

google_map(key = map_key, style = style) %>%
  add_polylines(data = flights, polyline = "polyline", mouse_over_group = "airport1",
                stroke_weight = 1, stroke_opacity = 0.3, stroke_colour = "#ccffff")

The end result

This dashboard has an example using a larger dataset and we have embedded the map into an R Shiny Dashboard. Click on the screenshot to try it out.