【问题标题】:How to make multiple pins/annotations appear?如何使多个引脚/注释出现?
【发布时间】:2021-05-04 22:43:12
【问题描述】:

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

导入基础 导入 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)")
            
        }
    }
}

}

【问题讨论】:

  • 请复制您的代码并粘贴到此处。代码图像难以阅读和调试。
  • 让注解 = MKPointAnnotation() ???

标签: ios swift annotations mapkit


【解决方案1】:

因为您一直在修改相同的 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)")
            
        }
    }
}

【讨论】:

  • 好答案。 (已投票。)除了不应该是MKPointAnnotation 而不是MKMapAnnotation吗?
  • 在浏览器窗口中输入代码而不是通过编译器运行代码的危险...
  • 是的。通常我对此很擅长,但我们都会偶尔犯错。
  • 你能帮我做吗?比如给我一些关于如何在每次迭代中创建一个新的提示
  • @EmHar 这就是我答案中的代码所做的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多