Skip to content

Instantly share code, notes, and snippets.

@alejandrofloresm
Created November 5, 2020 03:47
Show Gist options
  • Save alejandrofloresm/0d4fa0fd1967ce10094092113e4897cd to your computer and use it in GitHub Desktop.
Save alejandrofloresm/0d4fa0fd1967ce10094092113e4897cd to your computer and use it in GitHub Desktop.
Random Longitude and Latitude for a VBA function
' Based on https://gis.stackexchange.com/questions/334297/generate-coordinates-with-minimum-maximum-distance-from-given-coordinates
Public Function RandLatLng(latitude As Double, longitude As Double, maxMeters As Long, minMeters As Long)
Dim EarthRadius As Integer
Dim Degree As Double
Dim P_i As Double
Dim MaxKm As Long
Dim MinKm As Long
Dim The_R As Double
Dim The_Theta As Double
Dim Dx As Double
Dim Dy As Double
Dim nLat As Double
Dim nLng As Double
P_i = 3.14159265358979
EarthRadius = 6371
Degree = EarthRadius * 2 * P_i / 360 * 1000
MaxKm = maxMeters * 1000
MinKm = minMeters * 1000
The_R = ((MaxKm - MinKm + 1) * Rnd() ^ 0.5) + MinKm
The_Theta = Rnd() * 2 * P_i
Dy = The_R * Math.Sin(The_Theta)
Dx = The_R * Math.Cos(The_Theta)
nLat = latitude + Dy / Degree
nLng = longitude + Dx / (Degree * Math.Cos(latitude / 57.2957795130823))
RandLatLng = "" & CDbl(nLat) & ", " & CDbl(nLng)
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment