jjzjj

iOS SDK : MapKit MKPolyLine not showing

coder 2024-01-20 原文

我试图在我的 map 上显示折线,但该线没有显示。我尝试了很多东西,但注意似乎有效。

我检查了 Core Data 函数,它正在返回数据,所以这不是问题所在。它必须是我在 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;
}

最佳答案

显示的代码有两个问题:

  1. 折线是使用 MKMapPoint 创建的,它被错误地设置为纬度/经度值。 MKMapPoint 不是纬度/经度。它是平面 map 投影上纬度/经度的 x/y 变换。使用 MKMapPointForCoordinate 将纬度/经度值转换MKMapPoint,或者只使用CLLocationCoordinate2D。当您拥有纬度/经度时,只需使用 CLLocationCoordinate2D 就更容易编码和理解。
  2. viewForOverlay 中,代码正在创建一个空的 MKOverlayView,它是不可见的。创建一个 MKPolylineView(绘制 MKPolylineMKOverlayView 的子类)并设置它的 strokeColor


对于第一期,使用:

  • CLLocationCoordinate2D 而不是 MKMapPoint,
  • CLLocationCoordinate2DMake 代替 MKMapPointMake,
  • polylineWithCoordinates 而不是 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" 而不是 valueForKey:@"lat"(与 @"lng" 相同) .
  • 确保设置了 map View 的delegate,否则即使进行了所有其他更改,viewForOverlay delegate 方法也不会被调用。

关于iOS SDK : MapKit MKPolyLine not showing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16838360/

有关iOS SDK : MapKit MKPolyLine not showing的更多相关文章

随机推荐