'CLLocation'不能转换为'CLLocationCoordinate2D'

时间:2015-04-20 13:03:27

标签: ios swift cllocation cllocationcoordinate2d

我正在尝试使用多个教程来自学Swift。

到目前为止,我有这段代码。

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
    }
}

这一行

var annotation = CustomAnnotation(coordinate: manager.location, title: textView.text, subtitle: "SubTitle");

导致此错误:

  

'CLLocation'不能转换为'CLLocationCoordinate2D'

我的其他Swift文件是:

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
    }

}

2 个答案:

答案 0 :(得分:1)

错误消息非常明确。 init想要一个CLLocationCoordinate2D而你正试图给它一个CLLocation。我怀疑你想传递coordinate的{​​{1}}属性,而不是位置本身。

答案 1 :(得分:1)

CLLocation有一个名为" coordinate"的属性。 CLLocationCoordinate2D类型,因此您可以访问该字段并获取CLLocation的CLLocationCoordinate2D