Skip to content

Instantly share code, notes, and snippets.

@e-kotov
Last active January 25, 2016 16:30
Show Gist options
  • Save e-kotov/98451c625b2abc6c05b9 to your computer and use it in GitHub Desktop.
Save e-kotov/98451c625b2abc6c05b9 to your computer and use it in GitHub Desktop.
Showcase of creation and plotting of great circle lines
# this code showcases creation and plotting of great circle lines
# first install missing packages
# thanks to Pratik Patil for the package installation code ( http://stackoverflow.com/a/29622385 )
# Specify the list of required packages to be installed and load
Required_Packages = c("leaflet", "sp", "geosphere", "scales")
Install_And_Load <- function(Required_Packages) {
Remaining_Packages <- Required_Packages[!(Required_Packages %in% installed.packages()[,"Package"])]
if(length(Remaining_Packages))
{
install.packages(Remaining_Packages)
}
for(package_name in Required_Packages)
{
library(package_name, character.only = T, quietly = F)
}
}
# Call the Function
Install_And_Load(Required_Packages)
# sample code for drawing great circle lines
draw_great_circle_lines <- function() {
n = 20 # set number of random points - adjust to your liking, but be careful - too many points may slow down the rendering of the lines
# create a data table with random points - all points are approximately in Russia
x <- data.frame( oLat = runif(n, min = 50, max = 69), # origin lat
oLon = runif(n, min = 30, max = 170), # origin lon
dLat = runif(n, min = 50, max = 69), # destination lat
dLon = runif(n, min = 30, max = 170), # destination lon
value = runif(n, min = 100, max = 1000)) # random migration values
# create origin and destination points
oX <- x # copy data frame for origins
coordinates(oX) = ~ oLon + oLat # create spatial object
proj4string(oX) = CRS("+init=epsg:4326") # set coordinate system to WGS84
dX <- x # copy data frame for destinations
coordinates(dX) = ~ dLon + dLat # create spatial object
proj4string(dX) = CRS("+init=epsg:4326") # set coordinate system to WGS84
xPaths <- gcIntermediate(oX, dX, n = 50, addStartEnd = T, sp = T) # create great circle paths
xPaths <- SpatialLinesDataFrame(sl = xPaths, data = x["value"]) # attach the random migration values from original table
xPaths@data$value_scaled <- rescale( log(xPaths@data$value), to = c(1, 2)) # normalise the values to appropriate line widths
xPaths@data$value_opacity <- rescale( log(xPaths@data$value), to = c(0.05, 0.25)) # normalise the values to use for opacity
# plot object with leaflet
m = leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addPolylines(data = xPaths,
color = "red",
weight = xPaths@data$value_scaled,
opacity = xPaths@data$value_opacity,
popup = xPaths@data$value)
m
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment