Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapKit overlay does not appear

I'm trying to add a circle overlay to my map. I followed the apple docs and got this far, but the overlay doesn't appear when I run the app. Here's my code...

@IBOutlet var map: MKMapView!
let location = CLLocationCoordinate2DMake(40.73085, -73.99750)
let regionRadius: CLLocationDistance = 5500

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    let diskRenderer: MKCircleRenderer = MKCircleRenderer.init()
    diskRenderer.fillColor = UIColor.init(red: 0, green: 192, blue: 295, alpha: 1)
    return diskRenderer
}

override func viewDidLoad() {
    super.viewDidLoad()

    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location, regionRadius, regionRadius)
    map.setRegion(coordinateRegion, animated: true)
    let diskOverlay: MKCircle = MKCircle.init(centerCoordinate: location, radius: 5000)
    map.addOverlay(diskOverlay)

    // Do any additional setup after loading the view.
}

I'm teaching myself all this stuff so forgive me if i've made an obvious mistake.

like image 867
user3915477 Avatar asked Jul 06 '26 13:07

user3915477


2 Answers

See the accepted answer to this question: How to create MKCircle in Swift?

Steps are:

  1. Ensure this controller implements MKMapViewDelegate:

    class YourViewController: UIViewController, MKMapViewDelegate
    
  2. In viewDidLoad set the delegate on map to self:

    override func viewDidLoad() {
    super.viewDidLoad()
    map.delegate = self;`
    
  3. Add the following function to render the overlay (change the color, etc):

    func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    if let overlay = overlay as? MKCircle {
        let circleRenderer = MKCircleRenderer(circle: overlay)
        circleRenderer.fillColor = UIColor.blueColor()
        return circleRenderer
    }
    else {
       return MKOverlayRenderer(overlay: overlay)
    }
    } 
    
  4. The radius of your circle is too big as it is currently set and the whole map will be blue. Set it to something small, like 1000, so you can see the circle.

like image 177
markwatsonatx Avatar answered Jul 08 '26 06:07

markwatsonatx


objc in a class that is set as a mkmapviewdelegate:

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolygon class]]) {
        MKPolygon *polygon = (MKPolygon *)overlay;
        MKPolygonRenderer *renderer = [[MKPolygonRenderer alloc] initWithPolygon:polygon];
        renderer.strokeColor = [UIColor blueColor];
        renderer.lineWidth = 5.;
        return renderer;
    }
    return [[MKOverlayRenderer alloc] initWithOverlay:overlay];
}
like image 36
Anton Tropashko Avatar answered Jul 08 '26 06:07

Anton Tropashko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!