user2106875
user2106875

Reputation: 1

How to generate random LatLng coordinates in a polygon?

I need to generate random LatLng points in a polygon defined on the maps suppose my first point beging at (x,y) and next latlng will be greater than 100 meters and less that 500 meters

Upvotes: 0

Views: 616

Answers (2)

Marek R
Marek R

Reputation: 37717

This is quite simple.

  1. Get maximum and minimum values of latitude and longitude.
  2. generate random value of longitude (use uniform distribution).
  3. generate random value of latitude (you can use uniform distribution or take into account shape of the earth).
  4. check if random point is inside of polygon, if not then try again.

Upvotes: 0

SingleWave Games
SingleWave Games

Reputation: 2648

You could try something like below, this uses a HashMap to create unique and random numbers:

public void getRandomPosistions(int endPoint, int total)
{
    Set<Point> set = new HashSet<Point>();
    Random position = new Random();
    Point point;

    Point usedPos = new Point();
    // Starting Position
    usedPos.x = 100;
    usedPos.y = 100;
    set.add(usedPos);

    do
    {
        point = new Point();
        point.x=position.nextInt(endPoint);
        point.y=position.nextInt(endPoint);
        set.add(point);
    }
    while(set.size() < (total));

    List<Object> positionList = new ArrayList<Object>(set);
}

Upvotes: 1

Related Questions