我正在尝试按照 KML 文件中给我的坐标绘制一条线。我尝试使用几个 KML 解析器,但它们似乎都不起作用,所以我手动解析数据。您可以查看我在这个问题中使用的 KML 文件 here .
我能够获取坐标并通过将它们添加为注释来验证它们是否正确。它看起来像这样:
所以我看了几个制作折线的例子,但我想不出来。看着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,它包含仅包含 x 和 y 键以及坐标的 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/