2017-04-06 91 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