## BIO4115/9115 GBIF rgbif demo
## Dag Endresen, GBIF.no, UiO-NHM, dag.endresen@nhm.uio.no, dag.endresen@gmail.com

#install.packages("rgbif")
#install.packages("maps")
install.packages("mapproj")
install.packages("raster")


#library(rgbif) # r-package for accessing GBIF
require(rgbif) # r-package for accessing GBIF
require(maps)
require(mapproj)
require(mapdata)
require(maptools) # mapping tools for spatial objects
require(rgdal) # provides the Geospatial Data Abstraction Library
require(raster) # spatial raster data management, works well with dismo

key <- name_backbone(name="Hepatica nobilis", kingdom="Plantae")$speciesKey
sp <- occ_search(taxonKey=key, return="data", hasCoordinate=TRUE, limit=1000) 
gbifmap(sp)

sp_name <- "Hordeum vulgare" ## Choose your own species
key <- name_backbone(name = sp_name, kingdom="Plantae")$speciesKey
sp <- occ_search(taxonKey=key, return="data", hasCoordinate=TRUE, country="NO", limit=1000) 
gbifmap(sp, region = "norway")


## Extract coordinates
xy <- sp[c("decimalLongitude","decimalLatitude")] ## Only the coordnates
sp_xy <- sp[c("species", "decimalLongitude","decimalLatitude")] ## Input for Maxent

## Write dataframe to file
write.table(sp_xy, file="./sp_xy.txt", sep="\t", row.names=FALSE, qmethod="double") ## Input for Maxent

## Read data file back into R
rm(sp_xy)
sp_xy <- read.delim("./sp_xy.txt", header=TRUE, dec=".", stringsAsFactors=FALSE)

## Read environment data into R
env <- getData('worldclim', var='bio', res=10) # 10 degree resolution (approx 18 km)
#env <- getData('worldclim', var='bio', res=2.5) # 2 degree 5 minute resolution (approx 5 km)
plot(env, 1) # plot the first bioclim layer (BIO1 = Annual Mean Temperature)
plot(env, 12) # plot the first bioclim layer (BIO12 = Annual Precipitation)
points(xy, col='blue') # plot species occurrence points to the map

plot(env, 1, main="BioClim 1 (Annual Mean Temperature)")
points(xy, col='red', pch=20) # plot species occurrence points to the map (smaller dots)


