Reputation: 48495
In Ruby if I have a particular latitude and longitude, how can I generate a relatively random sample of points within a given radius or near another point?
{ latitude: 37.7905576, longitude: -122.3989885 }
Upvotes: 1
Views: 1586
Reputation: 7228
Theory
The circumference of the earth at equator = 40,076 km. The equator is divided into 360 degrees of longitude, so each degree at the equator represents approximately 111.32 km. Moving away from the equator towards a pole this distance decreases to zero at the pole.
1 degree aproximates to 111.32 km at equator.
96.41km at 30 degrees N/S
78.71 km at 45 degrees N/S
55.66 km at 60 degrees N/S
28.82 km at 75 degrees N/S
Therefor just adding or subtracting a random distance from the coordinates will not produce a "circle" . To avoid this we can generate a series of points and eliminating those outside the radius by using either Haversine,Spherical Law Of Cosines or Equirectangular projection.
As the latter uses only the common trig functions cos() I will use it to illustrate. Using php as I don't have Ruby
Application
function Equirectangular($lat1,$lng1,$lat2,$lng2){
$x = deg2rad($lng2-$lng1) * cos(deg2rad($lat1+$lat2)/2);
$y = deg2rad($lat1-$lat2);
$R = 6372.8; // gives d in km
$distance = sqrt($x*$x + $y*$y) * $R;
return $distance;
}
$centerLat = 37.7905576;
$centerLng = -122.3989885;
for ($i = 0; $i <= 200; $i++) {
$lat = rand(0,40000)/2;//Random between 0 & 2 =radius +- 2 degrees 222.62 km
$lng = rand(0,40000)/2;
$lat2 = $centerLat+ ($lat/10000);
$lng2 = $centerLng+ ($lng/10000);
echo $lat2." ".$lng2."";
if (Equirectangular($centerLat,$centerLng,$lat2,$lng2)< 200){//200 km
echo " In";
}else{
echo " Out";
}
echo "<br>";
}
Upvotes: 3