简体   繁体   中英

Annotations not showing on map

I'm trying to add annotations on the map using a list of locations coming from the server.

Json Data:

[{ "_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
   }
}]

I am using alamo fire to send a get request from the server to get the json data above in the viewWillAppear method.

    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)
        }
    }
}

And finally in the viewDidLoad method I use the storeList with the lat/long data to add the annotations.

   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)
    }
}

For some reason the annotations doesnt seem to show in the map when I run it. I seem to be doing the right way of adding annotations but maybe missed a small but important bit. Can anyone help?

You are using viewWillAppear wrong. You should make a request in viewDidLoad and do this inside request function (after data is loaded)

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)
}

because viewDidLoad is called before viewWillAppear , and because Alamofire request is async , which means, that it will be finished after viewDidLoad and viewWillAppear . So what happens is your array is empty, when you add annotations, and when your data is downloaded - nothing happens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM