iOS SDK:MapKit MKPolyLine没有显示

我正在尝试在地图上显示折线,但线条没有显示。 我尝试了很多东西,但注意到似乎有效。

我检查了核心数据函数,它正在返回数据,所以这不是问题。 它必须在我的mappoint创建中的某个地方或地图上的dwawing(我猜)。 我确定在某个地方肯定是一个小错误,但我找不到它。

我的代码:

- (void)viewDidLoad { [super viewDidLoad]; AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; mapView.delegate = self; } - (void)createLine { AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Logs" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entityDescription]; NSError *error; NSArray *logs = [context executeFetchRequest:request error:&error]; int logsCount = [logs count]; MKMapPoint points[logsCount]; // loop logs for (int i = 0; i < logsCount; i++) { MKMapPoint point; point = MKMapPointMake([[[logs objectAtIndex:i] valueForKey:@"lat"] doubleValue], [[[logs objectAtIndex:i] valueForKey:@"lng"] doubleValue]); points[i] = point; } MKPolyline *routeLine = [MKPolyline polylineWithPoints:points count:logsCount]; [mapView addOverlay:routeLine]; } - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay { MKOverlayView *mapOverlayView = [[MKOverlayView alloc] initWithOverlay:overlay]; return mapOverlayView; } 

显示的代码有两个问题:

  1. 使用MKMapPoint创建折线, MKMapPoint错误地设置为纬度/经度值。 MKMapPoint不是纬度/经度。 它是平面地图投影上纬度/经度的x / y变换。 使用MKMapPointForCoordinate 纬度/经度值转换MKMapPointForCoordinate或者仅使用CLLocationCoordinate2D 。 当你有lat / long时使用CLLocationCoordinate2D更容易编码和理解。
  2. viewForOverlay ,代码创建了一个不可见的空MKOverlayView 。 改为创建MKPolylineView (绘制MKPolylineMKOverlayView的子类)并设置其strokeColor

对于第一个问题,请使用:

  • CLLocationCoordinate2D而不是MKMapPoint
  • CLLocationCoordinate2DMake而不是MKMapPointMake
  • polylineWithCoordinates而不是polylineWithPoints

对于第二个问题,这是一个例子:

 - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay { if ([overlay isKindOfClass:[MKPolyline class]]) { MKPolylineView *mapOverlayView = [[MKPolylineView alloc] initWithPolyline:overlay]; //add autorelease if not using ARC mapOverlayView.strokeColor = [UIColor redColor]; mapOverlayView.lineWidth = 2; return mapOverlayView; } return nil; } 

其他几件事:

  • 而不是valueForKey:@"lat" ,我会使用objectForKey:@"lat" (对于@"lng" )。
  • 确保设置了地图视图的delegate ,否则即使进行了所有其他更改,也不会调用viewForOverlay委托方法。