如何让多个pins/annotations出现?
How to make multiple pins/annotations appear?
下面是我的代码。在第 30 行,当我将经度和纬度更改为 actual/hard 编码数字时,我可以在地图上看到图钉。但是当我捕获通过解码 json 对象返回的多个经度和纬度时,我打印了坐标,但它没有在地图上显示。任何帮助都会很棒!
导入基金会
导入 UIKit
导入 MapKit
class 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)")
}
}
}
}
因为您一直在修改相同的 self.annotation
,所以只会添加 一个 点,然后在循环的每次迭代中修改它。
您应该从视图控制器中删除 let annotation
属性 并在循环的每次迭代中创建一个 new:
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)")
}
}
}
下面是我的代码。在第 30 行,当我将经度和纬度更改为 actual/hard 编码数字时,我可以在地图上看到图钉。但是当我捕获通过解码 json 对象返回的多个经度和纬度时,我打印了坐标,但它没有在地图上显示。任何帮助都会很棒!
导入基金会 导入 UIKit 导入 MapKit
class 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)")
}
}
}
}
因为您一直在修改相同的 self.annotation
,所以只会添加 一个 点,然后在循环的每次迭代中修改它。
您应该从视图控制器中删除 let annotation
属性 并在循环的每次迭代中创建一个 new:
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)")
}
}
}