Function HAVERSINEDIST(proj_lat, proj_long, stat_lat, stat_long)
earth_radius = 3959 'miles
Pi = 3.14159265
deg2rad = Pi / 180
dLat = deg2rad * (stat_lat - proj_lat)
dLon = deg2rad * (stat_long - proj_long)
a = Sin(dLat / 2) * Sin(dLat / 2) + Cos(deg2rad * proj_lat) * Cos(deg2rad * stat_lat) * Sin(dLon / 2) * Sin(dLon / 2)
c = 2 * WorksheetFunction.Asin(Sqr(a))
d = earth_radius * c
HAVERSINEDIST = d
End Function
Function PTINPOLY(stat_coords As Variant, proj_lat As Double, proj_long As Double) As Boolean
Dim x As Long, m As Double, b As Double, poly As Variant, num_sides_crossed As Long
poly = stat_coords
For x = 1 To UBound(poly) - 1
If poly(x, 1) > proj_long Xor poly(x + 1, 1) > proj_long Then
m = (poly(x + 1, 2) - poly(x, 2)) / (poly(x + 1, 1) - poly(x, 1))
b = (poly(x, 2) * poly(x + 1, 1) - poly(x, 1) * poly(x + 1, 2)) / (poly(x + 1, 1) - poly(x, 1))
If m * proj_long + b > proj_lat Then num_sides_crossed = num_sides_crossed + 1
End If
Next
PTINPOLY = num_sides_crossed Mod 2
End Function
Function STATIONS(proj_lat As Double, proj_long As Double) As Variant
Dim stat_names(2) As Variant
Dim stat_coords(2, 1) As Variant
i = 3
With WorksheetFunction
stat_names(0) = .Index(['BDE VALUES'!$A$4:$A$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], 1), ['BDE VALUES'!$E$4:$E$178], 0)) '1st Closest Station Name
stat_coords(0, 0) = .Index(['BDE VALUES'!$C$4:$C$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], 1), ['BDE VALUES'!$E$4:$E$178], 0)) '1st Closest Station Latitude
stat_coords(0, 1) = .Index(['BDE VALUES'!$D$4:$D$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], 1), ['BDE VALUES'!$E$4:$E$178], 0)) '1st Closest Station Longitude
stat_names(1) = .Index(['BDE VALUES'!$A$4:$A$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], 2), ['BDE VALUES'!$E$4:$E$178], 0)) '2nd Closest Station
stat_coords(1, 0) = .Index(['BDE VALUES'!$C$4:$C$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], 2), ['BDE VALUES'!$E$4:$E$178], 0)) '2nd Closest Station Latitude
stat_coords(1, 1) = .Index(['BDE VALUES'!$D$4:$D$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], 2), ['BDE VALUES'!$E$4:$E$178], 0)) '2nd Closest Station Longitude
Do Until PTINPOLY(stat_coords, proj_lat, proj_long) = True
stat_names(2) = .Index(['BDE VALUES'!$A$4:$A$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], i), ['BDE VALUES'!$E$4:$E$178], 0)) 'ith Closest Station
stat_coords(2, 0) = .Index(['BDE VALUES'!$C$4:$C$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], i), ['BDE VALUES'!$E$4:$E$178], 0)) 'ith Closest Station Latitude
stat_coords(2, 1) = .Index(['BDE VALUES'!$D$4:$D$178], .Match(.Small(['BDE VALUES'!$E$4:$E$178], i), ['BDE VALUES'!$E$4:$E$178], 0)) 'ith Closest Station Longitude
i = i + 1
Loop
End With
STATIONS = WorksheetFunction.Transpose(stat_names)
End Function
Bookmarks