在Swift中实现"我的位置"按钮

DP2*_*P27 3 xcode mapkit ios currentlocation 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()
}
Run Code Online (Sandbox Code Playgroud)

}

我不确定的是,@IBAction func中的代码是什么,如果他们在寻找其他地方时偏离它,它将允许地图重新定位到用户的当前位置.

任何帮助将不胜感激.

非常感谢你!

Nir*_*v D 6

为此,您可以再次调用您的操作startUpdatingLocation方法.CLLocationManagerButton

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

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()                
}
Run Code Online (Sandbox Code Playgroud)

现在只需调用startUpdatingLocation您的按钮操作即可.

@IBAction func refLocation(_ sender: Any) {
    manager.startUpdatingLocation()
}
Run Code Online (Sandbox Code Playgroud)