MKMapView和addOverlay - 从kml解析叠加层

时间:2011-03-09 22:24:32

标签: iphone objective-c mkmapview overlay

我正在尝试为简单的iPhone应用制作地图叠加层。问题是,即使应用程序没有错误,折线也不会显示在地图上。控制台说[overlay lastObject]实际上是MKPolyline。有人可能会看到我在这里做错了什么...我是iPhone应用程序开发的新手?

这是我的mapView控制器的相关代码:

- (void)viewDidLoad {   
    [super viewDidLoad];    

    CGRect mapFrame = CGRectMake(0.0f, 31.0f, 320.0f, 370.0f);  
    mapView = [[MKMapView alloc] initWithFrame:mapFrame];

    MKCoordinateRegion region;
    MKCoordinateSpan span;
        span.latitudeDelta=.02;
        span.longitudeDelta=.02;

    CLLocationCoordinate2D location;
        location.latitude = 29.43421;
        location.longitude = -98.48436; 

        region.span=span;
        region.center=location; 

    NSURL *url = [NSURL URLWithString:@"They asked me not to post this... It is a valid KML file though"];
    kml = [[KMLParser parseKMLAtURL:url] retain];

    // Add all of the MKOverlay objects parsed from the KML file to the map.
    NSArray *overlay = [kml overlays];      
    NSLog(@"TEST: %@",[overlay lastObject]);

    [mapView setRegion:region animated:TRUE];
    [mapView regionThatFits:region];        
    [mapView addOverlay:[overlay lastObject]];

    [self.view insertSubview:mapView atIndex:0];    

    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bkgd.png"]];
    self.view.backgroundColor = background; 
    [background release];
    [url release];  

}

#pragma mark-
#pragma mark MKMapViewDelegate
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{       
    MKPolylineView *line = [[[MKPolylineView alloc] initWithPolyline:overlay] autorelease];
    line.strokeColor = [UIColor blueColor];
    line.lineWidth = 5;
    return line;
}

1 个答案:

答案 0 :(得分:12)

看起来没有设置地图视图的委托,在这种情况下,将永远不会调用viewForOverlay方法。在viewDidLoad中的MKMapView alloc + initWithFrame行之后,添加:

mapView.delegate = self;