Search code examples
iosswiftmkmapviewdelegate

removing specific mapView.overlay


I'm currently doing a project which involves mapView that needs to show a line that connects two points and circle around the user's location.

My code goes like this:

self.mapView.delegate = self // on viewDidLoad

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    switch overlay {
    case is MKCircle:
        let circle = MKCircleRenderer(overlay: overlay)
        circle.strokeColor = UIColor.blue
        //            circle.fillColor = UIColor(red: 0, green: 0, blue: 255, alpha: 0.1)
        circle.fillColor = UIColor.blue
        circle.lineWidth = 0.5
        circle.alpha = 0.1
        return circle
    case is MKPolyline:
        let polylineRenderer = MKPolylineRenderer(overlay: overlay)
        polylineRenderer.strokeColor = UIColor.black
        polylineRenderer.lineWidth = 2
        return polylineRenderer
    default:
        return MKPolygonRenderer()
    }
}

func createCircle(location: CLLocation){
    let circle = MKCircle(center: location.coordinate, radius: 500 as CLLocationDistance)
    self.mapView.add(circle)
}

func createPolyline() {
    var coords = [CLLocationCoordinate2D]()
    coords.append(point1)
    coords.append(point2)

    let polyline = MKPolyline(coordinates: coords, count: coords.count)
    self.mapView.add(polyline)
}

createCircle() and createPolyline() is called whenever the location changes so that it will also move to where the user is, my problem is that the previous overlays are kept, and the new ones overlap them. I've found a way to remove an overlay,

let overlays = mapView.overlays
mapView.removeOverlays(overlays)

But this line of code removes all the overlay, I only want to remove, for example, the previous Circle Overlay. Cant find a way to, for example, name a overlay so that I can have a reference to it when removing. Hope I was able to explain my situation well.

What's is the best way to solve this? Thanks!


Solution

  • You need to store your original MKOverlay object in a property, then you can simply call remove to remove it:

    class MyViewController: UIViewController {
    
        var circle: MKOverlay?
    
        func createCircle(location: CLLocation){
    
            self.removeCircle()
    
            self.circle = MKCircle(center: location.coordinate, radius: 500 as CLLocationDistance)
            self.mapView.add(circle!)
        }
    
        func removeCircle() {
            if let circle = self.circle {
                self.mapView.remove(circle)
                self.circle = nil
            }
        }
    }