3

I am loading multiple MKPolylines as overlays onto an MKMapView. I would like to be able to distinguish these some how so change things like color, line width, etc.

But, when viewForOverlay: gets called, it sees all my MKPolylines the same, which doesn't allow me to change any of them.

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {

    if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineView *aView = [[[MKPolylineView alloc] initWithPolyline:(MKPolyline*)overlay] autorelease];
        aView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        MKZoomScale currentZoomScale = (CGFloat)(mapView.bounds.size.width / mapView.visibleMapRect.size.width);
        aView.lineWidth = MKRoadWidthAtZoomScale(currentZoomScale);

        return aView;
    }

    // Want to color my next overlay red

    return  nil;
}

How can I do this? Could I somehow attach tag to each MKPolyline? Or, another, better way to do this?

Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412
  • Try [this answer](http://stackoverflow.com/questions/7464098/different-coloured-polygon-overlays). It's about polygons but it should work with polylines. –  Nov 17 '11 at 20:44
  • Anna, this is exactly what I wanted. Didn't realize it had a title property. Can you post this as an answer? – Nic Hubbard Nov 17 '11 at 21:07

3 Answers3

8

MKPolyline inherits from MKShape which has a settable title (and subtitle) property which you can use to tell them apart.

This answer has an example of how to use it with MKPolygon objects.

If title and subtitle are not sufficient for your requirements, then you can subclass as Mundi commented.

Community
  • 1
  • 1
0

i'm using mkcircle as an example

  MKCircle *circle = [MKCircle circleWithCenterCoordinate:currentPoint radius:radius];
    [circle setTitle:@"circle1"];
    [map addOverlay:circle];


- (MKOverlayView *)mapView:(MKMapView *)map viewForOverlay:(id <MKOverlay>)overlay
{
    NSLog(@"overlay %@",overlay);

    if ([[overlay title] isEqualToString:@"circle1"]){

    circleView = [[MKCircleView alloc] initWithOverlay:overlay];
    //circleView.strokeColor = [UIColor redColor];
    circleView.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.3];

    return circleView;
    }

}
chings228
  • 1,859
  • 24
  • 24
0

MKPolyLine is a subclass of UIView. Thus I would go with tags. This also makes it quite easy to refer to the lines when you need them (with viewWithTag) could be subclassed to add a tag-like identifier.

Mundi
  • 79,884
  • 17
  • 117
  • 140