我尝试在 map 上显示折线,但该线未显示。我尝试了很多方法,但注意到似乎有效。
我检查了核心数据函数,它正在返回数据,所以这不是问题。它必须是我在 map 点创建或 map 上绘制的某个地方(我猜)。 我确信一定是某个地方出了点小错误,但我找不到它。
我的代码:
- (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 <MKOverlay>)overlay
{
MKOverlayView *mapOverlayView = [[MKOverlayView alloc] initWithOverlay:overlay];
return mapOverlayView;
}
最佳答案
显示的代码有两个问题:
- 使用
MKMapPoint
创建折线时,该点的纬度/经度值设置不正确。MKMapPoint
不是纬度/经度。它是平面 map 投影上纬度/经度的 x/y 变换。使用MKMapPointForCooperative
将纬度/经度值转换为MKMapPoint
,或者仅使用CLLocationCooperative2D
。当您拥有纬度/经度时,仅使用 CLLocationCooperative2D 就更容易编码和理解。 - 在
viewForOverlay
中,代码创建了一个不可见的空MKOverlayView
。创建一个MKPolylineView
(绘制MKPolyline
的MKOverlayView
的子类)并设置其linesColor
。
对于第一期,请使用:
CLLocationCooperative2D
而不是MKMapPoint
,CLLocationCooperative2DMake
而不是MKMapPointMake
,- 和
polylineWithCooperatives
而不是polylineWithPoints
对于第二个问题,这里有一个例子:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)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;
}
其他一些事情:
- 我会使用
objectForKey:@"lat"
(与@"lng"
相同),而不是valueForKey:@"lat"
. - 确保设置了 map View 的
delegate
,否则即使进行所有其他更改,也不会调用viewForOverlay
委托(delegate)方法。
关于iOS SDK : MapKit MKPolyLine not showing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16838360/