问题描述
我正在尝试在iOS 4.0中的MKMapView上绘制MKPolygon。我有一个NSArray,其中包含自定义对象,包括纬度/经度属性。我在下面有一个代码示例:
I am trying to plot a MKPolygon on a MKMapView in iOS 4.0. I have an NSArray which contains custom objects that include properties for latitude/longitude. I have a code sample below:
- (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甚至是一个数组?有人可以清楚地说明这一点。
My question is how do i take my custom object contained in NSArray (coordinateData) and convert these object into an array of CLLocationCoordinate2d so that the Polygon can interpret and render? I'm not sure how CLLocationCoordinate2d is even an array? Can someone shed some clarity on this.
推荐答案
polygonWithCoordinates方法需要一个CLLocationCoordinate2D结构的C数组。您可以使用 malloc
为数组分配内存(并且 free
以释放内存)。循环遍历NSArray并将其设置为struct数组中的每个元素。
The polygonWithCoordinates method wants a C array of CLLocationCoordinate2D structs. You can use malloc
to allocate memory for the array (and free
to release the memory). Loop through your NSArray and set it each element in the struct array.
例如:
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方法应如下所示:
The viewForOverlay method should look like this:
- (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;
}
这篇关于iPhone MKMapView - MKPolygon问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!