Site icon R-bloggers

Mapping GPS Tracks in R

[This article was first published on Mollie's Research Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
This is an explanation of how I used R to combine all my GPS cycling tracks from my Garmin Forerunner 305.

Converting to CSV

You can convert pretty much any GPS data to .csv by using GPSBabel. For importing directly from my Garmin, I used the command:

gpsbabel -t -i garmin -f usb: -o unicsv -F out.csv

[Note: you’ll probably need to work as root to access your device directly]

For importing from a .tcx file, you can use:

gpsbabel -t -i gtrnctr -f test2.tcx -o unicsv -F old.csv

Mapping in R

After converting to .csv, we’ll have a file with several columns, such as latitude, longitude, date, and time. We can now easily import this into R.

gps <- read.csv("out.csv", 
 header = TRUE)

Next we want to load up ggmap and get our base map. To determine how zoomed in we are, we can set zoom and size. We can also choose the maptype, with options of terrain, satellite, roadmap, or hybrid (satellite + roadmap).

library(ggmap)
mapImageData <- get_googlemap(center = c(lon = median(gps$Longitude), lat = median(gps$Latitude)),
 zoom = 11,
# size = c(500, 500),
 maptype = c("terrain"))

I chose to set the center of the map to the median of my latitudes and the median of my longitudes. I’ve done some biking when traveling, so median made more sense for me than mean.
Finally we want to map our GPS data. There are several pch options to try.

ggmap(mapImageData,
 extent = "device") + # takes out axes, etc.
 geom_point(aes(x = Longitude,
  y = Latitude),
 data = gps,
 colour = "red",
 size = 1,
 pch = 20)

All my metro Atlanta bike rides
Previously, I’ve used Google Earth to create these maps, but I actually found it to be easier and way less time and resource efficient to do it in R. The only tricky part was converting the data into .csv, and there are other ways to do that, if GPSBabel isn’t working for you. You might also be interested in trying Google Earth for mapping your tracks, instead of R.

Here’s the gist with the code.

Citations and Further Reading

< !----->< !----->< !----->

To leave a comment for the author, please follow the link and comment on their blog: Mollie's Research Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.