以下是生成路径并将其作为覆盖添加到MKMapView 的方法。我将使用MKPolylineView,它是MKOverlayPathView 的子类,并且可以让您不必引用任何CGPath,因为您改为创建MKPolyline(包含路径的数据)并使用它创建MKPolylineView(地图上数据的可视化表示)。
MKPolyline 必须使用 C 点数组 (MKMapPoint) 或 C 坐标数组 (CLLocationCoordinate2D) 创建。遗憾的是 MapKit 没有使用更高级的数据结构,例如 NSArray,但就这样吧!我将假设您有一个CLLocation 对象的NSArray 或NSMutableArray 来演示如何转换为适合MKPolyline 的C 数据数组。这个数组被称为locations,你如何填充它将由你的应用程序决定——例如通过处理用户的触摸位置来填充,或者填充从网络服务下载的数据等。
在负责MKMapView的视图控制器中:
int numPoints = [locations count];
if (numPoints > 1)
{
CLLocationCoordinate2D* coords = malloc(numPoints * sizeof(CLLocationCoordinate2D));
for (int i = 0; i < numPoints; i++)
{
CLLocation* current = [locations objectAtIndex:i];
coords[i] = current.coordinate;
}
self.polyline = [MKPolyline polylineWithCoordinates:coords count:numPoints];
free(coords);
[mapView addOverlay:self.polyline];
[mapView setNeedsDisplay];
}
注意 self.polyline 在 .h 中声明为:
@property (nonatomic, retain) MKPolyline* polyline;
这个视图控制器也应该实现MKMapViewDelegate 方法:
- (MKOverlayView*)mapView:(MKMapView*)theMapView viewForOverlay:(id <MKOverlay>)overlay
{
MKPolylineView* lineView = [[[MKPolylineView alloc] initWithPolyline:self.polyline] autorelease];
lineView.fillColor = [UIColor whiteColor];
lineView.strokeColor = [UIColor whiteColor];
lineView.lineWidth = 4;
return lineView;
}
您可以使用 fillColor、strokeColor 和 lineWidth 属性来确保它们适合您的应用程序。我刚刚在这里画了一条简单、中等宽度的纯白线。
如果您想从地图中删除路径,例如用一些新的坐标来更新它,那么你会这样做:
[mapView removeOverlay:self.polyline];
self.polyline = nil;
然后重复上述过程,创建一条新的 MKPolyline 并将其添加到地图中。
虽然 MapKit 乍一看可能有点可怕和复杂,但可以很容易地做一些如本例所示的事情。唯一可怕的一点 - 至少对于非 C 程序员来说 - 是使用 malloc 创建缓冲区,使用数组语法将 CLLocationCoordinates 复制到其中,然后释放内存缓冲区。