ios - 在 MapView 上的点之间画一条线

标签 ios objective-c mkmapview

我正在尝试按照 KML 文件中给我的坐标绘制一条线。我尝试使用几个 KML 解析器,但它们似乎都不起作用,所以我手动解析数据。您可以查看我在这个问题中使用的 KML 文件 here .

我能够获取坐标并通过将它们添加为注释来验证它们是否正确。它看起来像这样:

Points on a map

所以我看了几个制作折线的例子,但我想不出来。看着this教程,我试过这个:

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    for (NSDictionary * c in points) {
        double x = [[c valueForKey:@"x"] doubleValue];
        double y = [[c valueForKey:@"y"] doubleValue];
        CLLocationCoordinate2D coordinate;
        coordinate.latitude = y;
        coordinate.longitude     = x;
        MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coordinate count:points.count];
    }
}

points 是一个 NSArray,它包含仅包含 xy 键以及坐标的 NSDictionaries。

但是,xcode 给我一个错误提示:

Sending 'CLLocationCoordinate2D' to parameter of incompatible type 'CLLocationCoordinate2D *'; take the address with &

如果我尝试在 coordinate 之前添加 &,它会在运行时出现BAD_ACCESS 错误。

我希望有一种更简单的方法可以做到这一点,并且你们中的一个可以帮助我理解这一点。

最佳答案

polylineWithCoordinates 方法需要一个指向 CLLocationCoordinate2D 结构的 C 数组 的指针。

当您只放置 coordinate 这是一个 CLLocationCoordinate2D 时,编译器会发出警告。

当您使用 &coordinate 发送指针时,编译器警告消失但 coordinate 本身仍然是单个 CLLocationCoordinate2D 结构。在运行时,该方法假定您给它的指针指向一个 CLLocationCoordinate2D 结构数组,尝试解释内存中之后单个坐标的内容(您尚未分配)导致“访问错误”。

for循环中,您需要将points NSArray中的所有坐标添加到您在循环之前分配的C数组中. 循环之后并且在 C 数组准备好所有坐标之后,然后您创建折线并将其添加到 map View 。例如:

//Declare C array big enough to hold the number of coordinates in points...
CLLocationCoordinate2D coordinates[points.count];

int coordinatesIndex = 0;

for (NSDictionary * c in points) {
    double x = [[c valueForKey:@"x"] doubleValue];
    double y = [[c valueForKey:@"y"] doubleValue];

    CLLocationCoordinate2D coordinate;
    coordinate.latitude = y;
    coordinate.longitude = x;

    //Put this coordinate in the C array...     
    coordinates[coordinatesIndex] = coordinate;

    coordinatesIndex++;
}

//C array is ready, create the polyline...
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coordinates count:points.count];

//Add the polyline to the map...
[self.mapView addOverlay:polyline];

不要忘记实现 rendererForOverlay 委托(delegate)方法:

-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineRenderer *pr = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        pr.strokeColor = [UIColor redColor];
        pr.lineWidth = 5;
        return pr;
    }

    return nil;
}

关于ios - 在 MapView 上的点之间画一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25025639/

相关文章:

ios - Swift 侧边栏菜单创建

objective-c - Cocos2d : CCMenu Item not responding to touch after resuming application

ios - 如何在交换事件中更改表格单元格中删除按钮的文本

ios - 在 map View 中显示动态注释图钉

ios - NS谓词问题

ios - 如何隐藏 MKMapView 上的蓝点和圆圈

ios - ios swift 中的核心数据分组不起作用

iphone - 如何检查电影是否正在播放? (如果可能的话)

android - 在 map 中显示折线路线后,如何设置相机位置以限定折线路线?

iphone - 检查 NavigationStack 是否包含 View Controller 错误