【问题标题】:Iterate through JSON array and add coordinates to the map遍历 JSON 数组并将坐标添加到地图
【发布时间】:2021-03-26 18:27:35
【问题描述】:

我正在使用API 来获取纬度和经度坐标,并将它们放置在地图上,并使用它对应的地点名称。我可以放置一个地方的经纬度坐标,但我不太确定如何将它们全部添加到地图中。我不知道该怎么做。我尝试使用 for 循环来做到这一点,但我太确定我将如何实现它。这是我到目前为止所得到的:

    func getData() {
        let url = "https://www.givefood.org.uk/api/2/foodbanks/"
        let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { [self] data, response, error in
            guard let data = data, error == nil else {
                print("Wrong")
                return
            }

            var result: [Info]?

            do {
                result = try JSONDecoder().decode([Info].self, from: data)
            }
            catch {
                print("Failed to convert: \(error.localizedDescription)")
            }
            guard let json = result else {
                return
            }
            
            for each in json {
                
                var each = 0
                each += 1
                
                let comp = json[each].lat_lng?.components(separatedBy: ",")
                
                let latString = comp![each]
                let lonString = comp![each]

                let lat = Double(latString)
                let lon = Double(lonString)
                
                let locationPin: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat!, lon!)
                
                let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(51.55573, -0.108312)
                
                let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMetres, longitudinalMeters: regionInMetres)
                
                mapView.setRegion(region, animated: true)

                let myAn1 = MapPin(title: json[each].name!, locationName: json[each].name!, coordinate: locationPin)
                
                mapView.addAnnotations([myAn1])
            }
        })
        task.resume()
    }

【问题讨论】:

    标签: ios arrays swift


    【解决方案1】:

    你的循环是错误的,eachfor 之后是一个Info 项目。 Int 索引 each 毫无意义,您在每次迭代中将其设置为零,因此您始终获得相同的坐标(在索引 1 处)。

    首先将namelat_lng 声明为非可选。所有记录都包含这两个字段。

    struct Info : Decodable {
        let lat_lng : String
        let name : String
    }
    

    其次,为了方便,扩展 CLLocationCoordinate2D 以从字符串创建坐标

    extension CLLocationCoordinate2D {
        init?(string: String) {
            let comp = string.components(separatedBy: ",")
            guard comp.count == 2, let lat = Double(comp[0]), let lon = Double(comp[1]) else { return nil }
            self.init(latitude: lat, longitude: lon )
        }
    }
    

    第三,将所有 good 代码放入 do 范围,而不是处理可选项,并在循环之前设置区域 once

    func getData() {
        let url = "https://www.givefood.org.uk/api/2/foodbanks/"
        let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { [self] data, response, error in
            if let error = error { print(error); return }
            
            do {
                let result = try JSONDecoder().decode([Info].self, from: data!)
                let location = CLLocationCoordinate2D(latitude: 51.55573, longitude: -0.108312)
                let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMetres, longitudinalMeters: regionInMetres)
                mapView.setRegion(region, animated: true)
                var pins = [MapPin]()
                for info in result {
                    if let coordinate = CLLocationCoordinate2D(string: info.lat_lng) {                      
                        pins.append(MapPin(title: info.name, locationName: info.name, coordinate: coordinate))
                        
                    }
                } 
                DispatchQueue.main.async {
                    self.mapView.addAnnotations(pins)
                }
            }
            catch {
                print("Failed to convert: \(error)")
            }
        })
        task.resume()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多