我在我的地图中添加了大约 3000 个 MKOverlay,正如您所想象的那样,这需要一段时间,有时长达大约 8 秒。我正在寻找一种使用线程来提高性能的方法,以便用户可以在添加叠加层时移动地图。优选地,将顺序添加覆盖,从地图区域内的覆盖开始。我用 GCD 尝试了一些类似的东西:
- (MKOverlayView*)mapView:(MKMapView*)mapView viewForOverlay:(id)overlay {
__block MKPolylineView* polyLineView;
//do the heavy lifting (I presume this is the heavy lifting part, but
// because this code doesn't compile, I can't actually *test* it)
// on a background thread
dispatch_async(backgroundQueue, ^ {
polyLineView = [[[MKPolylineView alloc] initWithPolyline:overlay] autorelease];
[polyLineView setLineWidth:11.0];
//if the title is "1", I want a blue line, otherwise red
if([((LocationAnnotation*)overlay).title intValue]) {
[polyLineView setStrokeColor:[UIColor blueColor]];
} else {
[polyLineView setStrokeColor:[UIColor redColor]];
}
//return the overlay on the main thread
dispatch_async(dispatch_get_main_queue(), ^(MKOverlayView* polyLineView){
return polyLineView;
});
});
}
但是因为 GCD 块是用void
参数和返回类型定义的,所以这段代码不起作用——我得到一个不兼容的指针类型错误return
。有什么我在这里遗漏的东西,或者另一种方法来解决这个问题吗?或者也许是一种完全不同的方法来提高叠加添加过程的性能?我感谢任何和所有的帮助!
编辑:
我发现问题不在于我在此处实际添加叠加层:
for(int idx = 1; idx < sizeOverlayLat; idx++) {
CLLocationCoordinate2D coords[2];
coords[0].latitude = [[overlayLat objectAtIndex:(idx - 1)] doubleValue];
coords[0].longitude = [[overlayLong objectAtIndex:(idx - 1)] doubleValue];
coords[1].latitude = [[overlayLat objectAtIndex:idx] doubleValue];
coords[1].longitude = [[overlayLong objectAtIndex:idx] doubleValue];
MKPolyline* line = [MKPolyline polylineWithCoordinates:coords count:2];
[line setTitle:[overlayColors objectAtIndex:idx]];
[mapViewGlobal addOverlay:line];
}
在这里添加所有 3000 可能需要 100 毫秒。需要很长时间的部分(我假设)是我实际创建叠加层的地方,在我展示的第一种方法中。