Ios 实施';我的位置';Swift中的按钮
目前,我正在尝试在地图上添加一个按钮,如果用户在地图上偏离该按钮,该按钮将重新显示用户的当前位置。目前,我有下面写的代码,显示用户的当前位置Ios 实施';我的位置';Swift中的按钮,ios,swift,xcode,mapkit,currentlocation,Ios,Swift,Xcode,Mapkit,Currentlocation,目前,我正在尝试在地图上添加一个按钮,如果用户在地图上偏离该按钮,该按钮将重新显示用户的当前位置。目前,我有下面写的代码,显示用户的当前位置 import UIKit import MapKit import CoreLocation class GameViewController: UIViewController,CLLocationManagerDelegate { var lastUserLocation: MKUserLocation?
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()
}
}
我不确定的是,在@iAction函数中放入什么代码,如果用户在查看其他位置时偏离了它,该函数将允许地图重新居中到用户的当前位置。为此,您可以在
按钮上再次调用startUpdatingLocation
方法CLLocationManager
要获得用户的正确当前位置,您需要从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()
}
我尝试时收到了一个NSExceptionimplementation@philhen27在你的问题中加上全部错误,如果可能,显示错误的屏幕截图too@philhen27在故事板中,您为名为location的按钮设置了错误的操作,只需删除与该按钮的连接,它就会对您起作用。@philhen27在故事板中,检查您是否设置了正确的按钮操作,并删除错误的按钮。