我正在使用 MKMapView 和 MKPolyline 来显示路线形状。当在我的 MKMapView 上放置注释并且已经存在另一个注释时,它将异步向我的路线提供者发送路由调用并添加形状覆盖。
这就是问题所在。如果我对请求使用主线程,它将在请求进行时冻结 MKAnnotation 下降,但当它返回时,它会很好地显示覆盖。相反,如果我将请求分派到异步队列,则注释删除中不会冻结,并且当异步调用完成时,它会添加叠加层,但 MapView 需要一段时间才能意识到这一点并实际绘制叠加层。有时需要20秒。这是代码。
//Action handler selector to drop the pin
-(void)dropWayPoint:(WayPoint*)wp prevWayPoint:(WayPoint*)prevWp {
[self.mapView addWayPoint: wp];
[self.routeService routeFrom:prevWp to:wp];
}
实际路线计算在这里:
@implementation RouteService
static dispatch_queue_t queue;
+(RouteService) initRouteService:(id)delegate {
RouteService *rs = [[RouteService alloc] init];
//Lots of things happen here, including the queue creation
...
if (!queue) {
queue = dispatch_queue_create("RouteDispatch.queue", NULL);
}
return rs;
}
//Lots of methods...
//then
-(void)routeFrom:(WayPoint*)wp to:(WayPoint*)wpTp {
dispatch_async(queue, ^{
//Code here
DirectionsRouteRequest *rt = [DirectionsRouteRequest buildWithRouteType:@"fastest"];
[rt addObjectToLocation:[wp coord]];
[rt addObjectToLocation:[wpTp coord]];
rt.options.routeType = @"fastest";
NSLog(@"Dispatching...");
//Now send the request
DirectionsResponseType *response = [MapUtil computeDirections:rt];
Leg *leg = [Leg buildFromResponse:response route: self.route startWayPoint:wp endWayPoint:wpTp];
MKPolyline *pl = [MapUtil makePolylineWithLocations:[leg routeShape]];
[self.route.legsHash setObject:pl forKey:leg.legIdStr];
//Add Overlay here!!!
[self.mapDeskViewController.mapView addOverlay: pl];
//Desperately advising map view to redraw itself and show the overlay
[self.mapDeskViewController.mapView setNeedsDisplay];
//I can see this being displayed very quickly, meaning
NSLog(@"Response, pl_count:%d",pl.pointCount);
//However it takes a long time after this returns to actually display the overlay.
});
}
如果我使用上面的代码并注释掉 async 指令,则需要相同的时间来处理它,这会引起烦人的冻结,但是会立即绘制覆盖层:
//Lots of methods...
//then
-(void)routeFrom:(WayPoint*)wp to:(WayPoint*)wpTp {
/* COMMENTED OUT ASYNC
dispatch_async(queue, ^{
*/
//Code here
DirectionsRouteRequest *rt = [DirectionsRouteRequest buildWithRouteType:@"fastest"];
[rt addObjectToLocation:[wp coord]];
[rt addObjectToLocation:[wpTp coord]];
rt.options.routeType = @"fastest";
NSLog(@"Dispatching...");
//Now send the request
DirectionsResponseType *response = [MapUtil computeDirections:rt];
Leg *leg = [Leg buildFromResponse:response route: self.route startWayPoint:wp endWayPoint:wpTp];
MKPolyline *pl = [MapUtil makePolylineWithLocations:[leg routeShape]];
[self.route.legsHash setObject:pl forKey:leg.legIdStr];
//Add Overlay here!!!
[self.mapDeskViewController.mapView addOverlay: pl];
//Desperately advising map view to redraw itself and show the overlay
[self.mapDeskViewController.mapView setNeedsDisplay];
//I can see this being displayed very quickly, meaning
NSLog(@"Response, pl_count:%d",pl.pointCount);
/*
COMMENTED OUT ASYNC
});
*/
}
知道为什么 MKMapView 需要一段时间才能意识到它需要在异步完成时绘制叠加层吗?
谢谢奥雷里奥