iosxcodemkoverlay

how to handle multiple MKOverlays in delegate function


I want to have a MKMapView with an two different overlays.

First, I have an "Image Overlay on the Map" (TileOverlay), and secondly I want to draw a route as an overlay on the Map.

Everything works fine if I do this stuff in two different projects (One with the image overlay, and the other with the route overlay)

Now, I am wondering how the viewForOverlay delegate function should look like if I merge my projects?

For my Image (tile) overlay i currently looks like this:

- (MKOverlayView *) mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{    
    TileOverlayView *tileView = [[TileOverlayView alloc] initWithOverlay:overlay];
    tileView.tileAlpha = 1.0;
    return tileView;
}

For my route Overlay it looks like this:

- (MKOverlayView*)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay 
{
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.lineJoin = kCGLineJoinRound;
    polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.4];
    return polylineView;
}

Now if i want to "merge" these (into one Project), how should this method look like?

 - (MKOverlayView*)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay 
{
    //what comes here?
}

Solution

  • You could deal with this situation by first checking the type of the overlay passed into your mapView:viewForOverlay: method, like this:

    - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
    
        if ([overlay isKindOfClass:[MKPolyline class]]) {   
    
            MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
            polylineView.lineJoin = kCGLineJoinRound;
            polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.4];
            return polylineView;
    
        } else {
    
            TileOverlayView *tileView = [[TileOverlayView alloc] initWithOverlay:overlay];
            tileView.tileAlpha = 1.0;
            return tileView;
        }