0

What I have:

  • Latitude/Longitude
  • Minimum distance in kilo meters eg 0.3
  • Maximum distance in kms eg 1.5

I have to pick a new location randomly which should be at least 0.3 kms and at max 1.5 kms away from the given location. ie This new location I have to choose can be anywhere between 0.3 km and 1.5 kms away from the given location in any direction.

Note: I have to implement this in Elixir(Programming) language but mathematical formula or pseudo code is fine

Radio Active
  • 449
  • 6
  • 18

1 Answers1

0

Another answer helped me to randomly generate a location uniformly in any direction. Below are the steps

  • dx = [0.3..0.7] x cos([0..2] x pi)
  • dy = [0.3..0.7] x sin([0..2] x pi)
  • some help from this answer
  • r_earth = 6378

and then you can do

new_latitude  = latitude  + (dy / r_earth) * (180 / pi);
new_longitude = longitude + (dx / r_earth) * (180 / pi) / cos(latitude * pi/180);

Here is implementation in Elixir language

def random_location_in_given_range(latitude, longitude, min_distance_in_km, max_distance_in_km) do
    random_distance =
    Enum.random(round(min_distance_in_km * 1000)..round(max_distance_in_km * 1000)) / 1000

    random_radian = Enum.random(0..200) / 100
    # dx = [0.3..0.7] x cos([0..2] x pi)
    dx = random_distance * :math.cos(random_radian * :math.pi())
    # dy = [0.3..0.7] x sin([0..2] x pi)
    dy = random_distance * :math.sin(random_radian * :math.pi())
    # radius of the earth in kilometer
    r_earth = 6378.137

    new_latitude = latitude + dy / r_earth * (180 / :math.pi())

    new_longitude =
    longitude + dx / r_earth * (180 / :math.pi()) / :math.cos(latitude * :math.pi() / 180)

    {new_latitude, new_longitude}
end
Radio Active
  • 449
  • 6
  • 18