我正在开发一个应用程序,该应用程序会在用户当前位置放置一个标记,并根据用户输入的位置放置其他标记。当前位置的注释已经被正确地放置了,但是当尝试放置用户输入的坐标时,注释没有被放置。
我已经使用map.addAnnotation(annotation)
正确地添加了注释,其中注释.coordinate(纽约)为CLLocationCoordinate2D(latitude: 40.713054, longitude: -74.007227999999998)
。
我发现viewForAnnotation
方法没有被调用,我认为这就是注释没有被放置的原因(打印注释不会输出任何结果)。我有一个测试应用程序,可以请求输入坐标并成功放置注释。在测试应用程序中,打印注释会输出一个值。
下面我粘贴了一些我认为与此问题相关的代码。如果需要更多信息,请评论。
import UIKit
import MapKit
import CoreLocation
class MapVC: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
map.delegate = self
}
下面这个函数从另一个类中获取数值并将其转换为CLLocationCoordinate2D类型的坐标。如上所述,annotation.coordinate (对于纽约)返回
CLLocationCoordinate2D(latitude: 40.713054, longitude: -74.007227999999998)
,因此add函数可以成功保存这些坐标。func add(newLocation location_one:[String:Any]) {
let momentaryLat = (location_one["latitude"] as! NSString).doubleValue
let momentaryLong = (location_one["longitude"] as! NSString).doubleValue
let annotation = MKPointAnnotation()
annotation.title = location_one["title"] as? String
annotation.coordinate = CLLocationCoordinate2D(latitude: momentaryLat as CLLocationDegrees, longitude: momentaryLong as CLLocationDegrees)
map.addAnnotation(annotation) //not sure if this adds the annotation!
self.map.centerCoordinate = annotation.coordinate
}
func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
return nil
}
let identifier = "pinAnnotation"
var annotationView = map.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
} else {
annotationView?.annotation = annotation
}
map.showAnnotations(map.annotations, animated: true)
return annotationView
}
add
方法是否被调用了? - Mihai Fratu