我正在尝试使用来自服务器的位置列表在 map 上添加注释。
Json 数据:
[{ "_id" : "589f3e299b64795df23a886b",
"name" : "Store 1",
"description" : "Most awesome store!",
"location" : {
"longitude" : -6.279025369998967,
"latitude" : 53.35487382895707
}
},
{
"_id" : "589f3e299b64795df23a886b",
"name" : "Store 2",
"description" : "Most awesome store!",
"location" : {
"longitude" : -6.267085527951536,
"latitude" : 53.33785738724761
}
}]
我正在使用 alamo fire 从服务器发送 get 请求,以在 viewWillAppear 方法中获取上面的 json 数据。
override func viewWillAppear(_ animated: Bool) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
mapView.showsUserLocation = false
var currentLocation = Location()
if let location = locationManager.location {
currentLocation = Location(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
}
//default to 10 km radius for now
let params = [
"latitude": currentLocation.getLatitude(),
"longitude": currentLocation.getLongitude(),
"radius": 10.0
] as [String : Any]
Alamofire.request("http://website.com/fyp/searchNearbyStores", parameters: params).responseJSON { response in
switch response.result {
case .success(let value):
let result = JSON(value)
print(result)
self.storeList = result.arrayValue.map({
Store(name: $0["name"].stringValue, description: $0["description"].stringValue, location: CLLocationCoordinate2D(latitude: $0["location"]["latitude"].doubleValue, longitude: $0["location"]["longitude"].doubleValue))
})
case .failure(let error):
print(error)
}
}
}
最后,在 viewDidLoad 方法中,我使用带有纬度/经度数据的 storeList 来添加注释。
override func viewDidLoad() {
super.viewDidLoad()
//zoom to current user location
if let location = locationManager.location {
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
for store in storeList {
let annotation = MKPointAnnotation()
annotation.title = store.getName()
annotation.subtitle = store.getDescription()
annotation.coordinate = store.getLocation()
mapView.addAnnotation(annotation)
}
}
由于某种原因,当我运行它时,注释似乎没有显示在 map 中。我似乎正在以正确的方式添加注释,但可能错过了一个小但重要的部分。有人可以帮忙吗?
最佳答案
您使用的viewWillAppear
错误。您应该在 viewDidLoad
中发出请求,并在请求函数内执行此操作(加载数据后)
if let location = locationManager.location {
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
for store in storeList {
let annotation = MKPointAnnotation()
annotation.title = store.getName()
annotation.subtitle = store.getDescription()
annotation.coordinate = store.getLocation()
mapView.addAnnotation(annotation)
}
因为 viewDidLoad
在 viewWillAppear
之前调用,并且因为 Alamofire
请求是异步
,这意味着它将在 viewDidLoad
和 viewWillAppear
之后完成。因此,当您添加注释和下载数据时,您的数组为空,什么也没有发生
关于json - 注释未显示在 map 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42180871/