Sunday, June 16, 2013

ggmap + animation = fly from Bologna to Copenhagen

This is something that one should do with something different than R.
I was looking for a free tool for creating a video from Google Maps: my goal was to input a start location, an end location, and obtaining a video zooming out from the start location then zooming in to the end location.

Not having found anything of my liking, I turned to R and a couple of its packages: ggmap and animation.

Surprisingly I did not need too many lines to get something close to the desired results.
Here's what I have done.

# load the packages
library(animation)
library(ggmap)
 
# you need ffmpeg.exe installed to obtain an .mp4 video!
# tell R where to find it on your PC
oopts <- ani.options(ffmpeg = "~your/path/to/ffmpeg.exe")
 
# starting location
startLoc <- "Aeroporto Marconi, Bologna, Italy"
# destination
endLoc <- "Kastrup Airport, Denmark"
 
# minimum level of detail (how high do you want to fly?)
minDetail <- 4
 
# maximum level of detail 
maxDetail <- 18
 
# convert location do lat/lon coordinates
startCoord <- geocode(startLoc)
endCoord <- geocode(endLoc)
 
# save video in .mp4 format (it takes a while to finish!)
saveVideo({
  # from ground to sky...
  for(i in maxDetail:minDetail){
    map <- get_map(location=c(startCoord$lon, startCoord$lat), zoom=i, maptype="satellite")
    print(ggmap(map, extent="device"))
  }  
  # ...from sky to ground
  for(i in minDetail:maxDetail){
    map <- get_map(location=c(endCoord$lon, endCoord$lat), zoom=i, maptype="satellite")
    print(ggmap(map, extent="device"))
  }
}, video.name="BLQ_CPH.mp4", other.opts = "-b 1200k"  # set the file name and the video bitrate
          , outdir="~my/video/folder")  # set the folder where you want to save the video
Created by Pretty R at inside-R.org


And here's a sample result, taking us from Bologna Airport to Kastrup Airport, near Copenhagen.



 I'd certainly like to have a smoother animation, but for that some more rolling-up-the-sleeves is needed!

Feel free to tell me what you think and to improve the code.

1 comment:

  1. I'm doing something similar. It looks like "interval" needs to be set to a number less than one. I'm going to start with 0.1 and see how it goes...

    ReplyDelete