R gists for maps

29 March 2014

Some R gists

The following is the R script which creates a heatmap from a zip file of Strava GPS traces. It makes an attempt to map the core of the activity by finding the mean and standard deviation of the traces latitudes and longitudes. It bounds on 3 std of the mean.

args <- commandArgs(trailingOnly = TRUE)
zipsPath <- "/data/"
dataPath <- "/tmp/"
outputFile <- file.path( "/maps", args[1] )

library(plotKML)

# unzip data from Strava
zips <- dir(zipsPath, pattern = "\\.zip")
for (i in 1:length(zips)) {
    unzip(file.path(zipsPath, zips[i]), exdir=dataPath)
}

# GPX files
files <- dir(dataPath, pattern = "\\.gpx")

# Consolidate routes in one data frame
index <- c()
latitude <- c()
longitude <- c()
for (i in 1:length(files)) {

    route <- readGPX(file.path(dataPath, files[i]))
    location <- route$tracks[[1]][[1]]

    index <- c(index, rep(i, dim(location)[1]))
    latitude <- c(latitude, location$lat)
    longitude <- c(longitude, location$lon)
}
routes <- data.frame(cbind(index, latitude, longitude))

# Map the routes
ids <- unique(index)

library("OpenStreetMap")

tiling = "stamen-watercolor"


    latmean <- mean(routes$latitude)
    latsd   <- sd(routes$latitude)

    longmean <- mean(routes$longitude)
    longsd   <- sd(routes$longitude)

    nw <- c(lat= latmean + 3 * latsd,   lon= longmean - 3 * longsd)
    se <- c(lat= latmean - 3 * latsd,   lon= longmean + 3 * longsd)

    map = openmap(nw, se, minNumTiles=9, type=tiling)
    map_longlat <- openproj(map, projection = "+proj=longlat +datum=WGS84")

    ras <- raster(map_longlat)

    png(outputFile, width=2*ras@ncols, height=2*ras@nrows)

    plotRGB(ras)

    for (i in 1:length(ids)) {
        currRoute <- subset(routes, index==ids[i])
        lines(currRoute$longitude, currRoute$latitude, lty="solid", col="#b8000065", lwd=6)
    }

dev.off()