Question

How to get Random Geo-points[ lat/long in decimal], placed anywhere inside a 100 meter radius circle? The center of the circle is another reference GeoPoint. Is there any Function/Formulae that implements this?

Basically I am reading the GPS input of my android device and need to generate random Geo-Points around the device [In a circle of radius 100 meters centered at my device].

Please note : There are no Geo-Points pre-stored in Database. I need to create all the Geo-points on the fly as mentioned above.

Was it helpful?

Solution

I just wrote a a Ruby method which extends Random to provide this.

Caveat: The points all lay within a box, not a circle.

class Random
  def location(lat, lng, max_dist_meters)

This is called with Random.new.location(mid_lat, mid_lng, dist). It will return a point which is probably within max_dist_meters of a the mid point.

    max_radius = Math.sqrt((max_dist_meters ** 2) / 2.0)

Without adjusting to max_radius we'd get points inside a square outside the circle (i.e. in the corners), where the distance would be greater than max_dist_meters. This constrains us to a square inside the circle which is probably more what you want.

    lat_offset = rand(10 ** (Math.log10(max_radius / 1.11)-5))
    lng_offset = rand(10 ** (Math.log10(max_radius / 1.11)-5))

The 1.11 and 5 come from here.

    lat += [1,-1].sample * lat_offset
    lng += [1,-1].sample * lng_offset
    lat = [[-90, lat].max, 90].min
    lng = [[-180, lng].max, 180].min

We should probably wrap around here instead of just clamping the value, fixes welcome.

    [lat, lng]
  end
end

Comments / clean up welcome!

Sample output here which you can see nicely if you paste the lat/lngs here.

OTHER TIPS

Pick random points on a square (i.e. pairs of uniform random numbers), then discard any that don't lie within a circle inscribed in that square. Given (x,y) pairs, a point is within your circle if:

(x - c_x)^2 + (y - c_y)^2 < r,

where (c_x, c_y) is the centre of your circle and r is its radius.

Start here: Generate a random point within a circle (uniformly). Then figure out how to center that circle at the reference lat/long. Then figure out how to map the randomly generated points to lat/long values. Hint: you want to add the individual components (say, x and y on your circle) to the circle's center.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top