作者:Boss-201411 | 来源:互联网 | 2023-02-13 14:19
这是我第一次在这里发帖.我目前陷入困境,试图找出如何在我的地图上添加一个按钮,如果他们在地图上偏离它,将重新显示用户的当前位置.目前我有下面写的代码显示用户的当前位置.
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 func中的代码是什么,如果他们在寻找其他地方时偏离它,它将允许地图重新定位到用户的当前位置.
任何帮助将不胜感激.
非常感谢你!
1> Nirav D..:
为此,您可以再次调用您的操作startUpdatingLocation
方法.CLLocationManager
Button
要获取用户的正确当前位置,您需要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()
}
现在只需调用startUpdatingLocation
您的按钮操作即可.
@IBAction func refLocation(_ sender: Any) {
manager.startUpdatingLocation()
}