Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 531
AdamBT Avatar asked Jun 08 '11 22:06

AdamBT


2 Answers

Your mapView has a method for getting the renderer object for a given overlay. You can then use the renderer to change the color of your overlay.

if let renderer = mapView.rendererForOverlay(overlay) as? MKPolygonRenderer {
    renderer.fillColor = UIColor.redColor()
}

Leave out the optional cast to MKPolygonRenderer if you're not looking for an MKPolygon overlay.

(I realize this is a rather old question, but I just stumbled across it and found my solution 😊)

like image 113
Kilian Avatar answered Oct 23 '22 08:10

Kilian


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];
like image 36
Chip Coons Avatar answered Oct 23 '22 08:10

Chip Coons