Skip to content

Instantly share code, notes, and snippets.

@cvitolo
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvitolo/f9d12402956b88935c38 to your computer and use it in GitHub Desktop.
Save cvitolo/f9d12402956b88935c38 to your computer and use it in GitHub Desktop.
Generate map of UK NRFA stations
#' Generate map of gauging stations.
#'
#' @author Claudia Vitolo <cvitolodev@gmail.com>
#'
#' @description This function takes as input a table of UK NRFA stations (output of getStationSummary() function) and generates a map using leaflet javascript library.
#'
#' @param selectedStationSummary This is the data.frame containing at least a column called "gridReference" (in which OS Grid references are stored) with 1 row for each station. Alternatively the table could contain 2 columns called "Latitude" and "Longitude" containing the coordinates of stations in WGS84, with 1 row for each station.
#'
#' @return displays a map
#'
#' @examples
#' myStations <- GetStationSummary(lonMin=-1, lonMax=1, latMin=51, latMax=49)
#' GenerateMap(myStations)
#'
GenerateMap <- function(selectedStationSummary){
library(devtools)
if(!require(rCharts)) install_github('ramnathv/rCharts')
# Load packages and sample data
library(zoo)
library(rCharts)
coords <- NULL
if ("Latitude" %in% names(selectedStationSummary) & "Longitude" %in% names(selectedStationSummary)) {
coords <- data.frame("Latitude"=unlist(selectedStationSummary$Latitude), "Longitude"=unlist(selectedStationSummary$Longitude))
}else{
if ("gridReference" %in% names(selectedStationSummary)) {
gridref <- unlist(selectedStationSummary$gridReference)
coords <- data.frame("Latitude"=unlist(lapply(gridref,function(x) OSG2LatLon(OSGParse(unlist(x)))[1])), "Longitude"=unlist(lapply(gridref,function(x) OSG2LatLon(OSGParse(unlist(x)))[2])))
}else{
message("Provide a table with at least 1 column called gridReference.")
}
}
if (!is.null(coords)){
centerCoords <- c(mean(coords$Latitude),mean(coords$Longitude))
myMap <- rCharts::Leaflet$new()
myMap$tileLayer(provider = 'Stamen.TonerLite')
myMap$setView(centerCoords, zoom = 6)
for (nStations in 1:dim(selectedStationSummary)[1]) {
myMap$marker(c(coords$Latitude[[nStations]],coords$Longitude[[nStations]]),
bindPopup = paste("<p> ", selectedStationSummary$name[[nStations]],
" id: ", selectedStationSummary$id[[nStations]],
" </p>", sep="") )
}
myMap
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment