如何使用MKOverlayPathView创建路径?

jow*_*wie 14 mapkit mkmapview cgpath ios

我一直在关注Apple的iOS类参考文档,不幸的是,没有人更明智.我已经下载了他们的示例代码,KMLViewer但是他们已经过于复杂了...我真正想知道的是如何生成路径并将其添加到MKMapView.文档讨论了使用a CGPathRef,但没有真正解释如何.

Rob*_*b B 20

以下是如何生成路径并将其作为叠加层添加到MKMapView.我将使用一个MKPolylineView,它是一个子类,MKOverlayPathView并且保护您不必引用任何,CGPath因为您改为创建一个MKPolyline(包含路径的数据)并使用它来创建MKPolylineView(数据的可视化表示)地图).

MKPolyline具有与C阵列的点(的创建MKMapPoint),或坐标的C数组(CLLocationCoordinate2D).令人遗憾的是,MapKit不使用更高级的数据结构NSArray,但它也是如此!我将假设您有一个NSArrayNSMutableArray多个CLLocation对象来演示如何转换为适合的C数据数组MKPolyline.这个数组被调用locations,你如何填充它将由你的应用程序决定 - 例如通过用户处理触摸位置填写,或填充从Web服务等下载的数据.

在负责以下的视图控制器中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];
}
Run Code Online (Sandbox Code Playgroud)

请注意,self.polyline在.h中声明为:

@property (nonatomic, retain) MKPolyline* polyline;
Run Code Online (Sandbox Code Playgroud)

此视图控制器还应实现该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;
}
Run Code Online (Sandbox Code Playgroud)

您可以使用fillColor,strokeColor和lineWidth属性来确保它们适合您的应用.我刚刚带着一条简单,适度宽的纯白线.

如果要从地图中删除路径,例如使用一些新坐标更新它,那么您将执行以下操作:

[mapView removeOverlay:self.polyline];
self.polyline = nil;
Run Code Online (Sandbox Code Playgroud)

然后重复上述过程以创建新的MKPolyline并将其添加到地图中.

虽然乍一看MapKit看起来有点可怕和复杂,但是可以很容易地做一些事情,如本例所示.对于非C程序员来说,唯一可怕的一点是使用malloc创建缓冲区,使用数组语法将CLLocationCoordinates复制到其中,然后释放内存缓冲区.