I am writing an app that has the ability to track a user's location and trace it on a map. There are three buttons, one that starts tracing the path that the user lays down, one is to stop tracing the path the user lays down, and the last is to clear the map of the traced line. I am having trouble setting up the clear button. Can someone please help me set up the @IBAction for the clear path button.
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var theMap: MKMapView!
@IBOutlet weak var startStopTracking: UISegmentedControl!
@IBOutlet weak var clearPath: UIButton!
@IBOutlet weak var label: UILabel!
var manager:CLLocationManager!
var myLocations: [CLLocation] = []
override func viewDidLoad() {
super.viewDidLoad()
//Setup our Location Manager
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
//manager.startUpdatingLocation()
//Setup our Map View
theMap.delegate = self
theMap.mapType = MKMapType.Hybrid
theMap.showsUserLocation = true
//Setup startStopTracking button?
startStopTracking.selectedSegmentIndex = -1
}
@IBAction func indexChanged(sender: UISegmentedControl) {
switch startStopTracking.selectedSegmentIndex
{
case 0:
manager.startUpdatingLocation()
case 1:
manager.stopUpdatingLocation()
default:
break;
}
}
@IBAction func clearPath(sender: UIButton) {
//label.text = String(myLocations.count)
//stopTracking()
//theMap.removeOverlay(overlay: MKOverlay) -> Void
}
func stopTracking() {
manager.stopUpdatingLocation()
myLocations = []
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
//theLabel.text = "\(locations[0])"
myLocations.append(locations[0] as CLLocation)
let spanX = 0.007
let spanY = 0.007
var newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
theMap.setRegion(newRegion, animated: true)
if (myLocations.count > 1){
var sourceIndex = myLocations.count - 1
var destinationIndex = myLocations.count - 2
let c1 = myLocations[sourceIndex].coordinate
let c2 = myLocations[destinationIndex].coordinate
var a = [c1, c2]
var polyline = MKPolyline(coordinates: &a, count: a.count)
theMap.addOverlay(polyline)
}
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 6
return polylineRenderer
}
return nil
}
}
You have to make your
polyline
a class property so you have access to it in your clearPath method: