# From Dyer et al. 2018 Molecular Ecology
#this is how I made a line that roughly follows the continental divide then plotted the distance of each population to that line.  Uses dist2line in r.  

### GPS coordinates to make the line:
### Mount_Garbitt	-122.80309	55.0496769
### Mount_Robson	-119	53.05
### Mount_Assiniboine	-115.65	50.8667
### Mt_Cleveland	-113.8481	48.925
### Scapegoat_Wilderness	-112.829273	47.309721
### Mt_Two_Top	-111.239116	44.624894

library(geosphere)
#read in the line using the above coordinates
line <- rbind(c(-122.80309, 55.0496769), c(-119,53.05), c(-115.65, 50.8667), c(-113.8481, 48.925), c(-112.829273, 47.309721), c(-111.239116, 44.624894))

#read in the points from a file
sites = read.csv("pop_coordinates_cline.csv", header=TRUE)
#pull out the spatial data
pops<-rbind(sites$longitude, sites$latitude)
#transpose the matrix so it has two columns not two rows
pops2<-t(pops)
d = dist2Line(pops2, line)

#plot it all on a graph
#plot the line
plot(makeLine(line), type='l')
#this shows the coordinates used to make the lines
points(line)
#plot the pops
points(pops2, col='blue', pch=20)
#make sure the pops are right by adding the pop names
text(sites$longitude, sites$latitude, sites$pop, pos=1, cex=1, offset=0.5)
#this plots where all the pops fall on the line
points(d[,2], d[,3], col='red', pch='x')
#this plots the line from each pop to the line
for (i in 1:nrow(d)) lines(gcIntermediate(pops2[i,], d[i,2:3], 10), lwd=2)

#show the output - I just copied into excel 
d
