Generate random coordinates around a location

后端 未结 4 1842
孤街浪徒
孤街浪徒 2021-02-02 11:18

I\'d like to have a function that accepts a geo location (Latitude, Longitude) and generates random sets of coordinates around it but also takes these parameters as a part of th

4条回答
  •  日久生厌
    2021-02-02 11:37

    as the other answer says, the simplest approach is going to be generating random points and then discarding ones that are too close to others (don't forget to check for min distance to central point too, if necessary).

    however, generating the random points is harder than explained. first, you need to select the radius at random. second, you need to have more points at large radii (because there's "more room" out there). so you cannot just make radius a uniform random number.

    instead, choose a number between 0 and $radius * $radius. then take the sqrt() of that to find the radius to plot at (this works because area is proportional to square of the radius).

    i don't know php (see the correction by Karolis in the comments), but from the other answer i think that would mean:

    $angle = deg2rad(mt_rand(0, 359));
    $radius = sqrt(mt_rand(0, $max_radius * $max_radius));
    

    then check that against the previous points as already described.

    finally, don't forget that you can reach a state where you can generate no more points, so you may want to put an upper limit on the "try and discard" loop to avoid hitting an infinite loop when the space is (close to) full.

    ps as a comment says on another answer, this is O(n^2) and so unsuitable for large numbers of points. you can address that to some extent by sorting the points by radius and only considering those within a difference of $min_distance, as long as $min_distance << $max_radius (as it is in your drawing); doing better than that requires a more complex solution (for example, at larger radii also using angle, or using a separate quad tree to store and compare positions). but for tens of points i imagine that would not be necessary.

提交回复
热议问题