我在地图上显示注释时遇到问题。它们仅在我移动或拖动地图时显示。
我试图遵循youtube上的教程以及c尖锐的问题之一
请给我一个帮助..这是代码
在这里我为注释创建了一个类
class customPin: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(pinTitle:String, pinSubTitle:String, location:CLLocationCoordinate2D) {
self.title = pinTitle
self.subtitle = pinSubTitle
self.coordinate = location
}}
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.register(CustomAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
self.locationManager.requestWhenInUseAuthorization()
//json show the list of the parks
pipiCanList()
//show location Barcelona
let location = CLLocationCoordinate2D(latitude: 41.3851 , longitude:2.1734)
let region = MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
self.mapView.setRegion(region, animated: true)
self.mapView.delegate = self
}
获取json信息
func pipiCanList(){
let url = "http://bluewave.lk/Apps/pipiCan/Api/read.php";
let urlObj = URL(string:url);
URLSession.shared.dataTask(with: urlObj!) {(data, response, error) in
do{
let pipiCans = try JSONDecoder().decode([pipiCanDBList].self, from: data!)
for pipiCan in pipiCans{
let Latitude = (pipiCan.ParkLatitude! as NSString).doubleValue
let Longitude = (pipiCan.ParkLongitude! as NSString).doubleValue
let location = CLLocationCoordinate2D(latitude: Latitude, longitude: Longitude)
//add to
let pin = customPin(pinTitle: pipiCan.ParkName!, pinSubTitle: pipiCan.Area!, location: location)
self.mapView.addAnnotation(pin)
}
} catch{
print ("Error - cannot get list")
}
}.resume()
}
}
答案 0 :(得分:0)
您需要
DispatchQueue.main.async {
let pin = customPin(pinTitle: pipiCan.ParkName!, pinSubTitle: pipiCan.Area!, location: location)
self.mapView.addAnnotation(pin)
}
由于URLSession.shared.dataTask
回调位于后台线程中,因此您应该在主线程中访问诸如mapView
之类的 UIKit 元素。您也可以
self.mapView.showAnnotations(self.mapView.annotations, animated: true)
在显示所有已添加注释的for循环之后,请记住在此处设置区域
let location = CLLocationCoordinate2D(latitude: 41.3851 , longitude:2.1734)
let region = MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
响应可能具有比上述区域远的位置值