Removing a circle on map?

This code to add a circle is working properly but I am unable to make the code work to remove the circle when I move the pin. I tried adding a remove function but that didn't work. Any suggestion where I am going wrong would be very much appreciated.


@IBAction func addAircraft(_ sender: UILongPressGestureRecognizer) {

let location = sender.location(in: self.mapView)

let locCoord = self.mapView.convert(location, toCoordinateFrom: self.mapView)

let annotation = MKPointAnnotation()

annotation.coordinate = locCoord

annotation.title = "Aircraft"

// addCircle(locCoord: locCoord)

self.mapView.removeAnnotations(mapView.annotations)

self.mapView.addAnnotation(annotation)

// self.mapView.remove(circle)

}


// MARK: Circle and Polygon overlays.


func addCircle(locCoord: CLLocationCoordinate2D) {

self.mapView.delegate = self

let circle = MKCircle(center: locCoord, radius: 1000 as CLLocationDistance)

self.mapView.add(circle)

}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

if overlay is MKCircle {

let circle = MKCircleRenderer(overlay: overlay)

circle.strokeColor = UIColor.red

circle.lineWidth = 1

return circle

}else {

return MKOverlayRenderer()

}

}

Accepted Reply

This will do it.


self.mapView.removeOverlays(self.mapView.overlays)

let location = sender.location(in: self.mapView)

let locCoord = self.mapView.convert(location, toCoordinateFrom: self.mapView)

let annotation = MKPointAnnotation()

annotation.coordinate = locCoord

annotation.title = "Aircraft"

addCircle(locCoord: locCoord)

self.mapView.removeAnnotations(mapView.annotations)

self.mapView.addAnnotation(annotation)

Replies

Is this about moving the pin -and- updating the circle, or just removing the circle?


See https://forums.developer.apple.com/message/272259#272259

Can you be more specific than “didn’t work”? The remove() call as written wouldn’t compile, I think, since you’re not keeping a reference to the circle overlay that you added. Perhaps you just need to get all the overlays and remove them all, just like you’re doing with annotations.

This will do it.


self.mapView.removeOverlays(self.mapView.overlays)

let location = sender.location(in: self.mapView)

let locCoord = self.mapView.convert(location, toCoordinateFrom: self.mapView)

let annotation = MKPointAnnotation()

annotation.coordinate = locCoord

annotation.title = "Aircraft"

addCircle(locCoord: locCoord)

self.mapView.removeAnnotations(mapView.annotations)

self.mapView.addAnnotation(annotation)