我有一个包含MKMapView的UIViewController。我通过以下代码在我的当前位置添加了一个注释:
import UIKit
import MapKit
class LocationViewController: UIViewController , MKMapViewDelegate ,CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager: CLLocationManager!
let regionRadius: CLLocationDistance = 1000
var token: dispatch_once_t = 0
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
if ((userLocation.coordinate.latitude != 0.0) && (userLocation.coordinate.longitude != 0.0)) {
dispatch_once(&token) {
self.centerMapOnLocation(userLocation.location!)
let annotation = MapPin(title: "This Location", locationName: "Test", discipline: "None", coordinate: userLocation.coordinate)
mapView.addAnnotation(annotation)
}
}
}
我希望注释能够随着用户拖动或移动地图视图而移动。例如,我的当前位置是新奥尔巴尼,如果我拖动地图而不是注释,它将在空中漂浮,直到我在Pontotoc上释放,然后注释指向我释放的位置。我会感激任何关于MapKit的提示或好的教程。