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; }
显示的代码有两个问题:
- 使用
MKMapPoint
创建折线,MKMapPoint
错误地设置为纬度/经度值。MKMapPoint
不是纬度/经度。 它是平面地图投影上纬度/经度的x / y变换。 使用MKMapPointForCoordinate
将纬度/经度值转换为MKMapPointForCoordinate
或者仅使用CLLocationCoordinate2D
。 当你有lat / long时使用CLLocationCoordinate2D
更容易编码和理解。 - 在
viewForOverlay
,代码创建了一个不可见的空MKOverlayView
。 改为创建MKPolylineView
(绘制MKPolyline
的MKOverlayView
的子类)并设置其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
委托方法。