我正从我的服务器加载一些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
上将这些数据显示为注释。
但是:不知何故,这些注释没有加载到地图上,即使我先“删除”,然后“添加”它们。
有什么建议吗?
答案 0 :(得分:0)
您将Station
个实例添加到某些self.annotations
媒体资源,而不是您的本地变量annotations
。因此,annotations
局部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!)
}