从当前位置添加注释

时间:2016-01-18 18:55:48

标签: ios swift xcode

当我点按一个按钮时,我想从用户位置添加注释。我猜它接近工作,但当我点击按钮时,它会在非洲的某个地方添加注释。 (纬度:0,经度:0)。为什么它不会显示正确的用户位置?

导入UIKit 导入MapKit 导入CoreLocation

类ViewController:UIViewController,CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()

}

@IBAction func addAnnotation(sender: UIBarButtonItem) {

    let addPin = MKPointAnnotation()
    addPin.coordinate = CLLocationCoordinate2D(latitude: self.mapView.userLocation.coordinate.latitude, longitude: self.mapView.userLocation.coordinate.longitude)
    addPin.title = "Hello world"
    mapView.addAnnotation(addPin)

}

}

1 个答案:

答案 0 :(得分:2)

您遇到的问题是您没有获得用户的位置。您需要在代码中添加一些内容才能实现此目的。我添加了整个代码,检查注释以获取描述。

import CoreLocation
import MapKit
import UIKit

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet var mapView: MKMapView!
    var locationManager = CLLocationManager()
    // Add two variables to store lat and long
    var lat = 0.0
    var long = 0.0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Check if you have the right to get the location
        self.locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
        }
    }

    override func viewWillAppear(animated: Bool) {
        // Start get the location on viewWillAppear
        locationManager.startUpdatingLocation()
    }

    @IBAction func addAnnoation(sender: AnyObject) {
        locationManager.startUpdatingLocation()
        let annotation = MKPointAnnotation()
        // Set the annotation by the lat and long variables 
        annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
        annotation.title = "User location"
        self.mapView.addAnnotation(annotation)
    }

    // To get the location for the user
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location:CLLocationCoordinate2D = manager.location!.coordinate
        lat = location.latitude
        long = location.longitude
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Error")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()


           // Dispose of any resources that can be recreated.
        }
    }

您还需要打开info.plist文件并添加以下属性:     NSLocationWhenInUseUsageDescription并添加一个字符串,以便您获取用户位置(这是强制性的,否则您将无法获取用户位置)。