在 Swift 中实现 'My Location' 按钮

Implementation of 'My Location' button in Swift

我目前正在尝试弄清楚如何在我的地图上添加一个按钮,如果用户在地图上偏离它,该按钮将重新显示用户的当前位置。目前,我在下面编写了显示用户当前位置的代码。

    import UIKit
    import MapKit
    import CoreLocation

   class GameViewController: UIViewController,CLLocationManagerDelegate
   {

var lastUserLocation: MKUserLocation?





@IBOutlet weak var Map: MKMapView!

let manager = CLLocationManager()





func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]

    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.00775, 0.00775)

    let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)

    let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
    Map.setRegion(region, animated: true)


    self.Map.showsUserLocation = true
    manager.stopUpdatingLocation()


}



override func viewDidLoad() {
    super.viewDidLoad()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()




}

@IBAction func refLocation(_ sender: Any) {
    print("click")
}





override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

我不确定的是,在 @IBAction 函数中放入什么代码,如果用户在看别处时偏离了用户当前位置,地图将重新居中到用户当前位置。

为此,您可以在 Button 操作中再次调用 CLLocationManagerstartUpdatingLocation 方法。

要获取用户的正确当前位置,您需要在 didUpdateLocations 方法中访问 location 数组中的 last 对象。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //Access the last object from locations to get perfect current location
    if let location = locations.last {        
        let span = MKCoordinateSpanMake(0.00775, 0.00775)        
        let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)        
        let region = MKCoordinateRegionMake(myLocation, span)
        Map.setRegion(region, animated: true)
    }               
    self.Map.showsUserLocation = true
    manager.stopUpdatingLocation()                
}

现在只需在您的按钮操作上调用 startUpdatingLocation

@IBAction func refLocation(_ sender: Any) {
    manager.startUpdatingLocation()
}