In two the previous posts about geojson, I described how you could get data from the USGS BISON API using our rbison package, and from the GBIF API using the rgbif package, then make a geojson file, and send to Github. In both examples, the data were points. What about polygons? This is a relatively common use case in which an area is defined on a map instead of points – and polygons are supported in geojson. How do we do this with the R to geojson to Github workflow?
Using our package rgbif you can get a interactive map with polygons up on Github in just four lines of code! Of course creating a .shp file will take more than four lines of code.
You'll need devtools packge to install rgbif from Github.
install.packages("devtools") library(devtools) install_github("rgbif", "ropensci", ref="newapi")
Make the map
There are various ways of getting a .shp file. I won't go over those here, so we'll just use a .shp file from the web. I downloaded a zip file for Abies magnifica for its range map from the book Atlas of United States Trees from this site – here is the link for the zip file: http://esp.cr.usgs.gov/data/little/abiemagn.zip. I unzipped the file locally on my machine, and here we just use the
abiemagn.shp file within that zip file.
The first line of code in the next code block uses the function
togeojson to make a geojson file, which is written locally on your machine (a message tells you where it is located, but you can specify where you want it to go with the
destpath parameter). Note that the input argument to
togeojson goes to the directory for
abiemagn/abiemagn.shp, but for this to work you need the associated other two files, in this case: abiemagn.dbf and abiemagn.shx.
The second line of code uses the
gist function to upload your .geojson file as a gist on Github.
file <- "~/abiemagn/abiemagn.shp" togeojson(input = file, method = "local", outfilename = "abiesmagmap")
## Success! File is at /Users/scottmac2/abiesmagmap.geojson
gist("~/abiesmagmap.geojson", description = "Abies magnifica polygons")
## Your gist has been published ## View gist at https://gist.github.com/sckott/7121053
That's it! The map is immediately available on the web, see here for the one we just created. And you can embed the map too, like here: