我正在編寫一個應用程序,並且我有一個嵌入的mapview來顯示用戶的位置。這是到目前爲止我的代碼:如何讓地圖在用戶位置上迅速居中?
class YourCurrentLocation: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
let regionRadius: CLLocationDistance = 1000
func checkLocationAuthorizationStatus() {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
mapView.showsUserLocation = true
centerMapOnLocation(locationManager.location!, map: mapView, radius: regionRadius)
} else {
locationManager.requestAlwaysAuthorization() //requestWhenInUseAuthorization()
}
}
func centerMapOnLocation(location: CLLocation, map: MKMapView, radius: CLLocationDistance) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
radius * 2.0, radius * 2.0)
map.setRegion(coordinateRegion, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// mapView.delegate = self
if CLLocationManager.locationServicesEnabled()
{
//locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
print("location enabled")
checkLocationAuthorizationStatus()
}
else
{
print("Location service disabled");
}
// Do any additional setup after loading the view.
}
}
我還添加了兩個條目,以我的plist:
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
,並在我的Xcode我已經設置爲模擬GPS數據在英國倫敦。
當我運行應用程序 - 我看到地圖,但倫敦沒有標記。我究竟做錯了什麼?
順便說一句,我不得不註釋掉該行:
//mapView.delegate = self
在
viewDidLoad()
,否則我有錯誤:
Cannot assign value of type YourCurrentLocation to type MKMapViewDelegate
,我不知道這是問題的一部分這裏。
我希望在顯示給用戶地圖時顯示效果,並在地圖上標出與他的位置一致的點。你能幫助我嗎?
''locationManager.location!'在你的代碼中會給你模擬器或設備的最後一個位置,這可能是任何東西。在我的回答中,我向你展示瞭如何使用'CLLocationManagerDelegate'來獲取實際的用戶位置。 – paulvs
好的,我明白了......謝謝!最後一個問題 - 在手機不在GPS範圍內的情況下會發生什麼情況,或者該位置還沒有被識別爲真實的? – user3766930
@ user3766930如果確實解決了您的問題,您可以將答案標記爲已接受。 – paulvs