在某个区域中创建随机CLLocationCoordinate

时间:2013-05-12 14:24:40

标签: ios objective-c random map

我有MKMapRect

如何在其中创建随机CLLocationCoordinate

我知道有arc4random(),但如何将其用于GPS坐标?

3 个答案:

答案 0 :(得分:5)

#define ARC4RANDOM_MAX      0x100000000
... 

//val is a double between 0 and 1
double xOffset = ((double)arc4random() / ARC4RANDOM_MAX);
double yOffset = ((double)arc4random() / ARC4RANDOM_MAX);
MKMapPoint randomPoint;

randomPoint.x = maprect.origin.x + xOffset*maprect.size.width;
randomPoint.y = maprect.origin.y + yOffset*maprect.size.height;

CLLocationCoordinate2D randomCoordinate = MKCoordinateForMapPoint(randomPoint);

答案 1 :(得分:2)

从MapRect,您可以获得MKMapPoint originMKMapSize size,然后随机CLLocationCoordinate应该是{origin.x + [0 ~ size.width], origin.y + [0 ~ size.height]}

typedef struct {
       MKMapPoint origin;
       MKMapSize size;
    } MKMapRect;
像这样的代码:

#define ARC4RANDOM_MAX      0x100000000
- (double)createRandomsizeValueFloat:(double)fromFloat toFloat:(double)toFloat
{
    if (toFloat < fromFloat) {
        return toFloat;
    } else if (toFloat == fromFloat) {
        return fromFloat;
    }
    return ((double)arc4random() / ARC4RANDOM_MAX) * (toFloat - fromFloat) + fromFloat;
}

//CLLocationDegrees lat = mapRect.origin.x + [self createRandomsizeValueFloat:0 toFloat:mapRect.size.width];
//CLLocationDegrees lng = mapRect.origin.y + [self createRandomsizeValueFloat:0 toFloat:mapRect.size.height];

答案 2 :(得分:0)

只需设置latitude个实例的longitudeCLLocationCoordinate属性。

注意范围:-90&lt;纬度&lt; 90,-180&lt;经度&lt; 180。

希望这有帮助。