2017-04-06 142 views
0

我試圖在谷歌地圖上顯示多個標記。但沒有加載。這是我的代碼。我使用Aifofire和SwiftyJSON。爲什麼多個標記不顯示在谷歌地圖上

class ViewController: UIViewController { 
    var Location: [Place] = [] 
     override func viewDidLoad() { 
      super.viewDidLoad() 
      _ = [Int : GMSMarker]() 
      let camera = GMSCameraPosition.camera(withLatitude: 0, longitude: 99, zoom: 6) 
      _ = GMSMapView.map(withFrame: CGRect.zero, camera: camera) 
      self.getInfoSchedule() 
     } 

這裏是我的功能,我解析來自JSON數據,並嘗試與地圖的工作:「爲什麼多個標記不會在谷歌地圖顯示」

func getInfoSchedule() { 
     var marker = [Int : GMSMarker]() 
     Alamofire.request("https://aqueous-depths-77407.herokuapp.com/earthquakes.json", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { 
      response in 
      switch response.result { 
      case .success(let value): 
       let json = JSON(value) 
       var i=0 
       for counter in json.arrayValue { 
        let lat = counter["latitude"].doubleValue 
        let long = counter["longitude"].doubleValue 
        let name = counter["place"].stringValue 
        let type = counter["usgs_ident"].stringValue 
        self.Location.append(Place(longitude:long,latitude:lat,name:name,type:type)) 
        print("latitude \(lat)") 
        marker[i] = GMSMarker() 
        marker[i]?.position = CLLocationCoordinate2DMake(lat, long) 
        marker[i]?.snippet = "Latitude: \(lat) Longitude: \(long)" 
        marker[i]?.map = mapView 
        marker[i]?.icon = GMSMarker.markerImage(with: UIColor.purple) 
        i += 1 
        print(i) 
       } 
       self.view = mapView 
      case .failure(let error): 
       print("Error: \(error)") 
      }}}} 
struct Place { 
    var longitude:Double 
    var latitude:Double 
    var name:String 
    var type:String 
} 

回答

1

要回答這個問題 - 這是因爲您只是簡單地製作for loop,但不使用它的索引,並且您正在製作其他變量i = 0,然後在循環完成後爲其賦值1。

我會寫更長的答案,因爲地圖是新的趨勢,許多其他人可能會發現它也有幫助。我花了很多時間來獲得這樣的工作。如果您想快速解答您的問題,請滾動並查看第4步。

我應該做的事情是以下幾點:

1 - 你想從你的服務器以獲取信息創建對象:

class Place: NSObject { 
    var longitude: Double 
    var latitude: Double 
    var name: String 
    var type: String 

    init(longitude: Double, latitude: Double, name: String, type: String) { 
     self.longitude = longitude 
     self.latitude = latitude 
     self.name = name 
     self.type = type 
    } 


    init?(dict: [String: JSON]) { 
     guard let longitude = dict["longitude"]?.doubleValue, let latitude = dict["latitude"]?.doubleValue, let name = dict["place"]?.stringValue, let type = dict["usgs_ident"]?.stringValue 
     else { return nil } 

     self.longitude = longitude 
     self.latitude = latitude 
     self.name = name 
     self.type = type 
    } 
} 

2 - 創建路由器。這是沒有必要的,但使它更清潔,可以很容易地使用你的頭內部的標記:

enum Router: URLRequestConvertible{ 
    case getAllPlaces 

    static let baseURLString = "https://aqueous-depths-77407.herokuapp.com"//This is your base url 

    var method: HTTPMethod{ 
     switch self { 
     case .getAllPlaces: 
      return .get 
     default: 
      return HTTPMethod(rawValue: "Could not determine method")! 
     } 
    } 

    var path: String{ 
     switch self { 
     case .getAllPlaces: 
      return "/earthquakes.json" 

     default: 
      return "Could not determine route" 
     } 
    } 

    // MARK: URLRequestConvertible 

    func asURLRequest() throws -> URLRequest{ 
     let url = try Router.baseURLString.asURL() 

     var urlRequest = URLRequest(url: url.appendingPathComponent(path)) 
     urlRequest.httpMethod = method.rawValue 

     if let token = Util.getApiToken(){ 
      urlRequest.setValue("bearer \(token)", forHTTPHeaderField: "Authorization") 
     } 



     return urlRequest 
    } 
} 

3 - 創建擴展,你處理你的請求,如API+Places.swift

extension API{ 

    //YOUR INFO 
    class func getInfo(completion: @escaping (_ error: Error?, _ place: [Place]?)->Void) { 
     Alamofire.request(Router.getAllPlaces().responseJSON{ response in 

      switch response.result{ 

      case .failure(let error): 
       completion(error, nil) 
       print(error) 

      case .success(let value): 
       let json = JSON(value) 
       print(json) 

       guard let dataArr = json["data"].array else { 
        completion(nil, nil) 
        return 
       } 

       var info = [Place]() 

       for data in dataArr { 
        if let data = data.dictionary, let info = Place.init(dict: data) { 
         info.append(info) 
        } 

       } 

       completion(nil, info) 

      } 
     } 

    } 
} 

4 - 終於搞定了信息:

創建對象數組:var placesArray = [Place]()

調用你的函數:

API.getInfo(){ 
    (error, inf: [Place]?) in 
    if let info = inf{ 
     self.placesArray = info 
    } 
    for location in self.placesArray{ 
     let marker = GMSMarker() 
     annotation.snippet = "\(location.latitude) \(location.longitude)" 
     annotation.position = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude) 
     annotation.map = self.mapView 
    } 
} 
self.view = self.mapView