我试图在iOS 4.0中的MKMapView上绘制一个MKPolygon.我有一个NSArray,它包含包含纬度/经度属性的自定义对象.我有一个代码示例如下:
- (void)viewDidLoad { [super viewDidLoad]; dataController = [[DataController alloc] initWithMockData]; coordinateData = [dataController getCordData]; CLLocationCoordinate2D *coords = NULL; NSUInteger coordsLen = 0; /* How do we actually define an array of CLLocationCoordinate2d? */ MKPolygon *polygon = [MKPolygon polygonWithCoordinates:coords count:coordsLen]; [mapView addOverlay: polygon]; } - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay { MKPolygonView *polygonView = [[MKPolygonView alloc] initWithPolygon: routePolygon]; NSLog(@"Attempting to add Overlay View"); return polygonView; }
我明白的是:
>我需要创建MKPolygon
> Ddd覆盖MapView
>这将转动将触发MKPolygonView的创建.
我的问题是如何使用NSArray(coordinateData)中包含的自定义对象,并将这些对象转换为CLLocationCoordinate2d的数组,以便Polygon可以解释和呈现?我不知道CLLocationCoordinate2d甚至是一个数组?有人可以清楚这一点.
解决方法
polygonWithCoordinates方法需要一个CLLocationCoordinate2D结构体的C数组.您可以使用malloc为阵列分配内存(并释放内存).循环遍历您的NSArray并将其设置为struct数组中的每个元素.
例如:
coordsLen = [coordinateData count]; CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * coordsLen); for (int i=0; i < coordsLen; i++) { YourCustomObj *coordObj = (YourCustomObj *)[coordinateData objectAtIndex:i]; coords[i] = CLLocationCoordinate2DMake(coordObj.latitude,coordObj.longitude); } MKPolygon *polygon = [MKPolygon polygonWithCoordinates:coords count:coordsLen]; free(coords); [mapView addOverlay:polygon];
viewForOverlay方法应如下所示:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay { MKPolygonView *polygonView = [[[MKPolygonView alloc] initWithPolygon:overlay] autorelease]; polygonView.lineWidth = 1.0; polygonView.strokeColor = [UIColor redColor]; polygonView.fillColor = [UIColor greenColor]; return polygonView; }