1

我有一个数组 NSMutableArray,我在其中保存了一个 MKuserlocation 类型 - locationArray。无论如何,现在我想从这个数组中获取数据并将其保存到 CLLocationCoordinate2D 类型的数组中。但是由于我保存在 locationArray 中的所有内容都来自 id 类型,我如何从中获取坐标并将其保存到第二个数组中?

  CLLocationCoordinate2D* coordRec = malloc(pathLength * sizeof(CLLocationCoordinate2D));
    for(id object in locationArray){
        for (int i = 0; i < pathLength; i++)
            ?????

我不知道这是否可能!

谢谢

4

3 回答 3

1

为什么需要一个 C 风格的 CLLocationCoordinate2D 对象数组?

干得好:

NSArray* userLocations; // contains your MKUserLocation objects...

CLLocationCoordinate2D* coordinates = malloc( userLocations.count * sizeof( CLLocationCoordinate2D) );

for ( int i = 0 ; i < userLocations.count ; i++ )
{
    coordinates[i] = [[[userLocations objectAtIndex: i] location] coordinate];
}
于 2013-05-20T17:05:28.287 回答
0

典型的解决方案是创建一个NSObject子类并定义一个属性 a CLLOcationCoordinate2D。实例化这些对象并将其添加到您的数组中。

@interface Coordinate : NSObject

@property (nonatomic) CLLocationCoordinate2D coordinate;

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate;

@end

@implementation Coordinate

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    self = [super init];
    if (self) {
        _coordinate = coordinate;
    }
    return self;
}

@end

然后,因为 yourlocationArray是一个数组MKUserLocation(它本身符合MKAnnotation),你可以这样做:

NSMutableArray *path;

path = [NSMutableArray array];
for (id<MKAnnotation> annotation in locationArray)
{
    // determine latitude and longitude

    [path addObject:[[Coordinate alloc] initWithCoordinate:annotation.coordinate]];
}

或者制作一个现有对象类型的数组,例如CLLocationorMKPinAnnotation或其他。

或者,如果此数组是要在地图上绘制的路径,您可能希望避免使用自己的数组,而是制作一个MKPolyline.

NSInteger pathLength = [locationArray count];
CLLocationCoordinate2D polylineCoordinates[pathLength];  // note, no malloc/free needed
for (NSInteger i = 0; i < pathLength; i++)
{
    id<MKAnnotation> annotation = locationArray[i];

    polylineCoordinates[i] = annotation.coordinate;
}
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:polylineCoordinates count:pathLength]
[self.mapView addOverlay:polyline];

这取决于这样做的目的是什么。但是,如果您可以使用避免mallocand的先前构造之一free,那可能是理想的。这些技术利用了 Objective-C 模式,使其更难泄漏、使用无效指针等。

于 2013-05-20T12:52:30.693 回答
0

参考苹果文档

您当然应该将CLLocationCoordinate2DMake函数与来自以下的数据一起使用MKUserLocation或直接从中提取信息MKUserLocation

object.location.coordinate // it's a CLLocationCoordinate2D from your 'object' example

或者

CLLocationCoordinate2DMake(object.location.coordinate.latitude, object.location.coordinate.longitude)

希望这有帮助。

于 2013-05-20T13:04:14.533 回答