为什么多个标记不会显示在谷歌地图上

时间:2017-04-06 22:46:19

标签: ios swift google-maps alamofire

我想在谷歌地图上显示多个标记。但没有任何负担。这是我的代码。我使用Alamofire和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解析数据并尝试使用map:

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
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我在Swift4中的解决方案

STRUCT:

struct Lugares : Codable {
    let id : Int?
    let latitude : String?
    let longitude : String?
    let place : String?

}

private var marcadores = [Lugares]()

Json与CODABLE:

// json map
func jsonMap() {

guard let mapUrl = URL(string: "https://aqueous-depths-77407.herokuapp.com/earthquakes.json") else { return }


    URLSession.shared.dataTask(with: mapUrl) { (data, response, error) in

        if error == nil {
            do {
                self.marcadores = try JSONDecoder().decode([Lugares].self, from: data!)


                DispatchQueue.main.async {

                    for state in self.marcadores {


                        //the coordinates obtained are string we convert into Double
                        let lat = Double(state.latitude!)
                        let long = Double(state.longitude!)

                        let state_marker = GMSMarker()
                        state_marker.position = CLLocationCoordinate2D(latitude: lat!, longitude: long!)
                        let aa = state_marker
                        print(aa)
                        state_marker.title = state.place
                        state_marker.snippet = "Hey, this is \(state.place!)"
                        state_marker.map = self.mapView



                    }


                }

            } catch let jsonError{
                print("An error occurred + \(jsonError)")
            }
        }
        }.resume()

}
// end func json map

结果: