iPhone MKMapView - MKPolygon Issues
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.
For example:
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];
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;
}
For iOS 7.0 and later we should use MKPolygonRenderer
instead of MKPolygonView
,
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
MKPolygonRenderer * polygonView = [[MKPolygonRenderer alloc] initWithPolygon:overlay];
polygonView.fillColor = [UIColor greenColor];
polygonView.strokeColor = [UIColor redColor] ;
polygonView.lineWidth = 1.0;
return polygonView;
}