Search code examples
objective-cios4xcode4mapkit

Changing color of an MKOverlay that has already been added to a mapview


I have some MKOverlays(actually they are MKPolygons) that are loaded as soon as the map shows up. I would like to change their color dynamically. The only way I can see of doing this, is to remove the overlay then add it back with the new color. Is there a better way to do this on the existing overlay?

I am brand new at objective-c/xcode/ios ... so please be gentle :)


Solution

  • It is important to remember that much of MapKit has different objects (MKPolygon, MKCircle, MKShape) to hold the data related to drawing a view (MKPolygonView, MKCircleView, MKOverlayView, etc.) In many cases you want to get a reference to the view object so you can then set the background color. i.e.

    MKOverlayView *anOverlay;  //You need to set this view to the object you are interested in
    anOverlay.backgroundColor = [UIColor redColor]; 
    [anOverlay setNeedsDisplay];
    

    If your object is an MKPolygon, you should determine the MKPolygonView it is being drawn into an then set the fillColor property and redraw the object by calling setNeedsDisplay:

    MKPolygonView *theView;
    theView.fillColor = [UIColor redColor];
    [theView setNeedsDisplay];