在Swift中的MKMapView中显示当前位置和更新位置 [英] Show Current Location and Update Location in MKMapView in Swift
问题描述
我正在学习如何使用新的Swift语言(只有Swift,没有Objective-C)。要做到这一点,我想用地图(MKMapView)做一个简单的视图。我想查找并更新用户的位置(例如在Apple Map应用程序中)。
I am learning how to use the new Swift language (only Swift, no Objective-C). To do it, I want to do a simple view with a map (MKMapView). I want to find and update the location of the user (like in the Apple Map app).
我试过这个,但没有发生任何事情:
I tried this, but nothing happened:
import MapKit
import CoreLocation
class MapView : UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
}
你能帮我吗?
推荐答案
您必须覆盖 CLLocationManager.didUpdateLocations
(CLLocationManagerDelegate的一部分)以在位置管理器检索当前位置时收到通知:
You have to override CLLocationManager.didUpdateLocations
(part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last{
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
}
注意:如果您的目标是iOS 8或更高版本,则必须在Info.plist中包含 NSLocationAlwaysUsageDescription
或 NSLocationWhenInUseUsageDescription
键才能获得工作的位置服务。
NOTE: If your target is iOS 8 or above, you must include the NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
key in your Info.plist to get the location services to work.
这篇关于在Swift中的MKMapView中显示当前位置和更新位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!