使用“ MKMapView”缩放多个位置

时间:2018-11-27 12:52:07

标签: ios swift mkmapview

我正在使用下面的代码从MySQL检索数据,以使用Swift在MKMapView上显示多个位置。

数据和位置显示在地图上,但是我不知道是如何调整缩放比例以覆盖该区域中的所有位置。

 func parseJSON(_ data:Data) {
        var jsonResult = NSArray()

        do {
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
        } catch let error as NSError {
            print(error)
        }

        var jsonElement = NSDictionary()
        let locations = NSMutableArray()

        for i in 0 ..< jsonResult.count
        {
            jsonElement = jsonResult[i] as! NSDictionary

            let location = LocationModel()

            //the following insures none of the JsonElement values are nil through optional binding
            if let evIdL = jsonElement["id"] as? String,
               let evUserNameL = jsonElement["username"] as? String,
               let evNotikindL = jsonElement["notikind"] as? String,
               let evLatiL = jsonElement["lati"] as? String,
               let evLongiL = jsonElement["longi"] as? String,
               let evLocatL = jsonElement["locat"] as? String,
               let evTimedateL = jsonElement["timedate"] as? String,
               let evDistanceL = jsonElement["distance"] as? String
            {
                location.evId = evIdL
                location.evUsername = evUserNameL
                location.evNotikind = evNotikindL
                location.evLati = evLatiL
                location.evLongi = evLongiL
                location.evLocat = evDistanceL
                location.evTimedate = evTimedateL
                location.evDisatnce = evDistanceL
                location.evLocat = evLocatL

                // the code to show locations
                let latiCon = (location.evLati as NSString).doubleValue
                let longiCon = (location.evLongi as NSString).doubleValue

                  let annotations = locations.map { location -> MKAnnotation in
                     let annotation = MKPointAnnotation()
                     annotation.title = evNotikindL
                     annotation.coordinate = CLLocationCoordinate2D(latitude:latiCon, longitude: longiCon)
                     return annotation
                }

                self.map.showAnnotations(annotations, animated: true)
                self.map.addAnnotations(annotations)
            }

            locations.add(location)
        }

        DispatchQueue.main.async(execute: { () -> Void in
            self.itemsDownloaded(items: locations)
        })
    }

我正在使用PHP文件连接MySQL,因为我说代码可以正常工作并显示位置,但是缩放仅集中在一个位置。

1 个答案:

答案 0 :(得分:1)

您可以尝试

DispatchQueue.main.async {
    self.map.addAnnotations(annotations)
    self.map.showAnnotations(annotations, animated: true)
    // make sure itemsDownloaded needs main ??
    self.itemsDownloaded(items: locations)

}