I am trying to make use of multiple tutorials to teach myself Swift.
So far I have this code.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate
{
@IBOutlet weak var myMapView: MKMapView!
var manager:CLLocationManager!
var myLocations: [CLLocation] = []
@IBOutlet weak var textView: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Setup our Location Manager
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
textView.delegate = self
//Setup our Map View
myMapView.delegate = self
myMapView.mapType = MKMapType.Satellite
myMapView.showsUserLocation = true
}
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: myMapView.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
myMapView.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)
myMapView.addOverlay(polyline)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
var annotation = CustomAnnotation(coordinate: manager.location, title: textView.text, subtitle: "SubTitle");
myMapView.addAnnotation(annotation)
textView.resignFirstResponder()
return true
}
}
This line
var annotation = CustomAnnotation(coordinate: manager.location, title: textView.text, subtitle: "SubTitle");
is causing this error:
'CLLocation' is not convertible to 'CLLocationCoordinate2D'
My other Swift file is:
import UIKit
import MapKit
class CustomAnnotation: NSObject, MKAnnotation {
var coordinate:CLLocationCoordinate2D
var title:NSString!
var subtitle: NSString!
init(coordinate: CLLocationCoordinate2D, title: NSString!, subtitle: NSString!) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
The error message is fairly explicit. The init
wants a CLLocationCoordinate2D
and you're trying to give it a CLLocation
instead. I suspect you want to pass the coordinate
property of manager.location
rather than the location itself.