1

So far i've tried generating random latitude and longitude and validating it with "CLLocationCoordinate2DIsValid". But the problem is i never get the coordinate within my specified "CLCircularRegion". Following is the logic i've written:

    CLLocationCoordinate2D myCoordinates = { currentLocationLatitude, currentLocationLongitude };

    CLCircularRegion *myRegion = [[CLCircularRegion alloc] initWithCenter:myCoordinates radius:160934 identifier:@"myID"];


    for (int i=0; i< 15; i++) {

    double latitude = (arc4random()%20) + (myCoordinates.latitude);
    double longitude = (myCoordinates.longitude)  + arc4random()%10;

    CLLocationCoordinate2D randomCoordinate = CLLocationCoordinate2DMake(latitude, longitude);

        if(CLLocationCoordinate2DIsValid(randomCoordinate) != NO)
        {
            NSLog(@"randomCoordinate: %f  %f", randomCoordinate.latitude, randomCoordinate.longitude);
            if([myRegion containsCoordinate:randomCoordinate])
            {
                NSLog(@"Point contains inside your region.");
            }
        }

    }

Is anything wrong with this implementation or is there any other way to find random points?

RoHaN
  • 372
  • 3
  • 14

1 Answers1

2

Your code is right. The only thing is that if you add +1 to latitude and +1 to longitude you will get the distance 138 km but your radius is 160 km. So, basically you can add only +1 to lat/long but not 10 or 20...Or you need to increase the radius... use link to check the distances: http://www.movable-type.co.uk/scripts/latlong.html

kabarga
  • 803
  • 6
  • 11
  • Yes right, but if add a constant value every time, like +1 or -1 it will generate same set of coordinates again for same current location. That's why i've included "arc4random()", to generate new values every time. But i need a more clean solution. – RoHaN Oct 02 '14 at 08:24
  • probably you need the method to get a random double between -1 and 1 to plus to lat/long but not random ints. – kabarga Oct 02 '14 at 08:39
  • Well i've updated the random lat/long logic with this one: double latitude = ((arc4random()%100) + (myCoordinates.latitude * 100))/100; double longitude = ((myCoordinates.longitude * 100) - (arc4random()%100))/100; – RoHaN Oct 02 '14 at 08:43
  • 1
    use something like: drand48()+myCoordinates.latitude and drand48()+myCoordinates.longitude. drand48() is a random double between 0 and 1. – kabarga Oct 02 '14 at 08:48