首页 > 解决方案 > 如何使多个引脚/注释出现?

问题描述

这是我下面的代码。在第 30 行,当我将经度和纬度更改为实际/硬编码数字时,我可以在地图上看到图钉。但是,当我捕获通过解码 json 对象返回的多个经度和纬度时,我得到了打印的坐标,但它没有显示在地图上。任何帮助都会很棒!

导入 Foundation 导入 UIKit 导入 MapKit

类 MapKitViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!

let annotation = MKPointAnnotation()


override func viewDidLoad() {
    super.viewDidLoad()
    AuthorizationLogin.getStudentLocation(completion: handleStudentLocation(location:error:)
    )
}
func handleStudentLocation(location: [StudentLocationStruct], error: Error?) {
    DispatchQueue.main.async {
        for locations in location {
            let latitude =  CLLocationDegrees(locations.latitude)
            let longitude = CLLocationDegrees(locations.longitude)
            self.annotation.coordinate = CLLocationCoordinate2D(latitude: latitude , longitude: longitude)
            self.mapView.addAnnotation(self.annotation)
            
            print("Latitude \(latitude)")
            print("Longitude \(longitude)")
            
        }
    }
}

}

在此处输入图像描述

标签: iosswiftannotationsmapkit

解决方案


因为您一直在修改相同self.annotation的内容,所以只会添加一个点,然后在循环的每次迭代中都会对其进行修改。

您应该let annotation从视图控制器中删除您的属性,并在循环的每次迭代中创建一个新属性:

func handleStudentLocation(location: [StudentLocationStruct], error: Error?) {
    DispatchQueue.main.async {
        for locations in location {
            let latitude =  CLLocationDegrees(locations.latitude)
            let longitude = CLLocationDegrees(locations.longitude)
            let annotation = MKPointAnnotation()
            annotation.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) 
            self.mapView.addAnnotation(annotation)
            
            print("Latitude \(latitude)")
            print("Longitude \(longitude)")
            
        }
    }
}

推荐阅读