我正在从服务器加载一些GeoData,并想显示它们并抛出注释:

Alamofire.request("http://localhost:1234/app/data").responseJSON { response in
    switch response.result {
    case .success(let value):
        let json = JSON(value)
        var annotations = [Station]()
        for (key, subJson):(String, JSON) in json {
            let lat: CLLocationDegrees = subJson["latitude"].double! as CLLocationDegrees
            let long: CLLocationDegrees = subJson["longtitude"].double! as CLLocationDegrees
            self.annotations += [Station(name: "test", lat: lat, long: long)]
        }

        DispatchQueue.main.async {
            let allAnnotations = self.mapView.annotations
            self.mapView.removeAnnotations(allAnnotations)
            self.mapView.addAnnotations(annotations)
        }

    case .failure(let error):
        print(error)
    }
}


和我的Station类:

class Station: NSObject, MKAnnotation {
    var identifier = "test"
    var title: String?
    var coordinate: CLLocationCoordinate2D

    init(name:String, lat:CLLocationDegrees, long:CLLocationDegrees) {
        title = name
        coordinate = CLLocationCoordinate2DMake(lat, long)
    }
}


所以我所做的基本上是:

从远程服务加载数据,并将这些数据作为注释显示在MKMapView上。

但是:不知何故这些注释不会加载到地图上,即使我先“删除”,然后又“添加”它们。

有什么建议么?

最佳答案

您要将Station实例添加到某些self.annotations属性,而不是局部变量annotations。因此,annotations local var仍然只是那个空数组。

显然,您可以通过引用annotations而不是self.annotations来解决此问题:

var annotations = [Station]()
for (key, subJson): (String, JSON) in json {
    let lat = ...
    let long = ...
    annotations += [Station(name: "test", lat: lat, long: long)] // not `self.annotations`
}


或者您可以使用map,完全避免这种潜在的混乱:

let annotations = json.map { key, subJson -> Station in
    Station(name: "test", lat: subJson["latitude"].double!, long: subJson["longitude"].double!)
}

10-08 06:07