-2

我正在尝试显示一个带有两个标记的地图,这些标记具有从 API 检索到的经度和纬度。

获取经度和纬度的函数被调用Viewdidload

 override func viewDidLoad() {
    super.viewDidLoad()

    getCurrent()

还有用于显示带有标记的地图的代码,viewdidload因此我的完整代码如下所示:

var longFamily  = ""
let latFamily = ""
var latShop = "" 
var longShop = "" 


override func viewDidLoad() {
    super.viewDidLoad()

    getCurrent()
    let coordinate₀ = CLLocation(latitude: CLLocationDegrees(Int(latFamily)!), longitude: CLLocationDegrees(Int(longFamily)!))
    let coordinate₁ = CLLocation(latitude: (Int(latFamily)!, longitude: (Int(longFamily)!))
    let distanceInMeters = coordinate₀.distance(from: coordinate₁) // result is in meters
    let floatDistance = Float(distanceInMeters)


    // get two markers with shop and client locations



    map.delegate = self

    // 2.
    let sourceLocation = CLLocationCoordinate2D(latitude: (Int(latFamily)!, longitude: (Int(longFamily)!)
    let destinationLocation = CLLocationCoordinate2D(latitude: (Int(latShop)!, longitude: (Int(latShop)!)

我知道在地图加载之前我必须做一些事情来获取数据,但不确定在哪里。感谢您的帮助

GetCurrent 函数调用 API:

 Alamofire.request(url!, method: .get, parameters: param,encoding: URLEncoding.default, headers: headers).responseJSON { response in



        if let value: AnyObject = response.result.value as AnyObject? {
            //Handle the results as JSON


            let data = JSON(value)
            self.LongShop = data["shopLong"] 
     // this is for family locations too  
4

1 回答 1

0

如果您想在地图加载之前获得坐标,则需要在加载视图之前(调用之前viewDidLoad)进行 API 调用。您可以尝试viewWillAppear,但根据 API 的响应时间,这可能不可靠。我建议您在获得数据后立即调用 API。事先从用户或所需来源获取param(可能在不同的视图中),并将其传递给prepareForSegue函数中的地图视图:

  1. 向地图视图添加一个全局变量(例如 MapViewController.swift)

    class MapViewController {
        var param: Any?    // replace Any with the desired data type
        /* rest of MapView code */
    }
    
  2. 进行 API 调用并传入之前的 View Controller 并将其传递给 MapViewController

    class PreviousViewController {
        var param: Any?    // replace Any with the desired data type
    
        override func viewDidLoad() {
            super.viewDidLoad()
            getFromAPI()    // getFromAPI being a function that makes the API call and assigns the param variable
        }
    
        func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let dest = segue.destination as? MapViewController {
                dest.param = self.param
            }
        }
    }
    

最重要的是,您可以添加 MapViewController segue 直到param不是nil

于 2017-05-17T14:55:58.633 回答