mat*_*mat 5 mkmapview mkannotation ios swift
当用户像Careem应用一样对地图进行拼写时,我想将MKAnnotaion保持在屏幕中央:
到目前为止,我设法显示了图钉,更新了图钉的位置,但是当我滚动地图时,代码中的注释最初移动了,然后又回到中心。我希望别针保持在中心。
@IBOutlet var mapView: MKMapView!
var centerAnnotation = MKPointAnnotation()
var manager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager() //instantiate
manager.delegate = self // set the delegate
manager.desiredAccuracy = kCLLocationAccuracyBest // required accurancy
manager.requestWhenInUseAuthorization() // request authorization
manager.startUpdatingLocation() //update location
var lat = manager.location.coordinate.latitude // get lat
var long = manager.location.coordinate.longitude // get long
var coordinate = CLLocationCoordinate2DMake(lat, long)// set coordinate
var latDelta:CLLocationDegrees = 0.01 // set delta
var longDelta:CLLocationDegrees = 0.01 // set long
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)
self.mapView.setRegion(region, animated: true)
centerAnnotation.coordinate = mapView.centerCoordinate
self.mapView.addAnnotation(centerAnnotation)
}
func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {
centerAnnotation.coordinate = mapView.centerCoordinate;
}
Run Code Online (Sandbox Code Playgroud)
****更新****
根据安娜的建议,我已在地图上添加了视图。这里的代码:
var newPoint = self.mapView.convertCoordinate(mapView.centerCoordinate, toPointToView: self.view)
var pinImage = UIImage(named: "yoga_pins.png")
var imageView = UIImageView(image: pinImage) // set as you want
imageView.image = pinImage
imageView.backgroundColor = UIColor.clearColor()
imageView.contentMode = UIViewContentMode.Center
imageView.center.y = newPoint.y
imageView.center.x = newPoint.x
self.view.addSubview(imageView)
Run Code Online (Sandbox Code Playgroud)
唯一的问题是,第一次加载地图时,位于上的注释(mapView.centerCoordinate我将使用该注释)来获取经度和纬度:

当我然后滚动地图时,图钉将移动到正确的位置(在图像下方):
func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {
centerAnnotation.coordinate = mapView.centerCoordinate;
}
Run Code Online (Sandbox Code Playgroud)
