2016-01-18 4 views
2

Я хочу добавить аннотацию из пользовательского местоположения, когда я нажимаю кнопку. Он близок к работе, я думаю, но когда я нажму кнопку, он добавит аннотацию в Африку. (широта: 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) 

} 

}

ответ

2

Проблема у вас есть то, что you're не получает места для пользователь. Для этого вам нужно добавить несколько вещей в свой код. Я добавил весь код, проверьте комментарии для описания.

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 и добавить строку, почему вам нужно, чтобы получить местоположение пользователя (это обязательно иначе вы не сможете получить местоположение пользователя) ,

+1

Вы мужчина! – jonask

Смежные вопросы