我正在尝试显示一张带有两个标记的地图,其中包含从 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)!)
我知道在地图加载之前我必须做一些事情来获取数据,但不确定在哪里。我将不胜感激你的帮助
获取当前函数调用 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
如果要在加载地图之前获得坐标,则需要在加载视图之前(在调用viewDidLoad
之前(进行 API 调用。您可以尝试viewWillAppear
,但根据 API 的响应时间,这可能不可靠。我建议在获得数据后立即调用 API。事先从用户或所需源获取param
(可能在不同的视图中(,并将其传递给 prepareForSegue
函数中的地图视图:
-
将全局变量添加到地图视图(例如.swift地图视图控制器(
class MapViewController { var param: Any? // replace Any with the desired data type /* rest of MapView code */ }
-
进行 API 调用并传入上一个视图控制器并将其传递给 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 } } }
除此之外,您还可以添加在未param
之前无法执行 MapViewController segue 的功能nil