DEV Community

Andre Henrique Rodrigues Perez
Andre Henrique Rodrigues Perez

Posted on

Easy way to pick a random geographic coordinate inside a radius in Python

First of all, let's use the haversine package. We will use the inverse haversine function to get a random calculation given a coordinate and a radius.

The inverse haversine function needs a coordinates pair as the starting point of the calculations, a distance representing the radius, and a direction, which can be an Enum (Cardinal points, represented by multiples of Pi) or a float number.

Also, we need to pass an Enum representing the Distance Unit. The valid values are given by the haversine.Unit class:

class Unit(Enum):
    """
    Enumeration of supported units.
    The full list can be checked by iterating over the class; e.g.
    the expression `tuple(Unit)`.
    """

    KILOMETERS = 'km'
    METERS = 'm'
    MILES = 'mi'
    NAUTICAL_MILES = 'nmi'
    FEET = 'ft'
    INCHES = 'in'
    RADIANS = 'rad'
    DEGREES = 'deg'
Enter fullscreen mode Exit fullscreen mode

So you may already get what the secret is: we'll select two random numbers, one for distance, and another for direction.

Let's begin:

from haversine import inverse_haversine, Unit


def random_coordinates(coords, radius, unit):
    """
    args - coords (Tuple: (lat: float, lng: float)), radius (float), unit (haversine.Unit enum)
    returns - new_coords (Tuple: (lat: float, lng: float))
    """

    # Choosing a random float between 0 and 2π
    random_direction = uniform(0.0, pi * 2)

    random_distance = uniform(0.0, radius)

    new_coords = inverse_haversine(
            point=coords,
            distance=random_distance,
            direction=random_direction,
            unit=unit
        )

    return new_coords
Enter fullscreen mode Exit fullscreen mode

Top comments (0)