如何通过点击按钮

时间:2015-07-08 02:54:40

标签: swift mapkit core-location

我想这样做,当点击一个按钮时,会保存设备的当前位置。然后,在当前位置的地图上显示一个图钉。我该怎么做呢?我正在使用swift。

import UIKit
import CoreLocation
import MapKit


class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var myPosition = CLLocationCoordinate2D()

    @IBOutlet var Map: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
        println("Updating Location \(newLocation.coordinate.latitude) , \(newLocation.coordinate.longitude) ")

        myPosition = newLocation.coordinate



        let span = MKCoordinateSpanMake(0.0009, 0.0009)
        let region = MKCoordinateRegion(center: newLocation.coordinate, span: span)
        Map.setRegion(region, animated: true)
    }

1 个答案:

答案 0 :(得分:0)

如果您正确处理授权请求,则locationManager didUpdateLocation应设置myPosition属性。

ViewController添加一个按钮并创建IBAction以处理内部事件的修饰。在IBAction中,您拨打Map.addAnnotation。添加的注释具有多个属性,即coordinate,您可以使用myPosition

在开始添加注释之前,请确保locationManager didUpdateLocation确实有效。有些事情需要处理,比如正确检查授权并添加NSLocationWhenInUseDescription ...