我正在尝试使用地图套件中的swift 3来自API的坐标(lat,long)绘制折线,但无法制作折线

时间:2017-06-03 18:58:29

标签: ios swift3 mapkitannotation

import UIKit
import MapKit
import CoreLocation
import AddressBook

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var TheMap: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        zoomToRegion()
        location()
    }

    func centerMapOnLocation(location: MKPointAnnotation, regionRadius: Double) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
                                                                  regionRadius * 2.0, regionRadius * 2.0)
        TheMap.setRegion(coordinateRegion, animated: true)

    }



    //MARK:- MapViewDelegate methods

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polylineRenderer = MKPolylineRenderer(overlay: overlay)

        if overlay is MKPolyline {
            polylineRenderer.strokeColor = UIColor.blue
            polylineRenderer.lineWidth = 5

        }
        return polylineRenderer
    }



    //MARK:- Zoom to region

    func zoomToRegion() {
        let location = CLLocationCoordinate2D(latitude: 28.618945, longitude: 77.377347400000005)
        let region = MKCoordinateRegionMakeWithDistance(location, 5000.0, 7000.0)
        TheMap.setRegion(region, animated: true)
    }

    // API CALL FUNCTION

    func location() {

        let user = "userid"
        let password = "password"

        let postString = ["empid":user, "date1": password]
        var request = URLRequest(url:URL(string: "http://mydomainhere.com/airtel_hrm/webapi/api/getpunchdeytails")!)
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)

        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?)in

            if error != nil
            {
                print("error=\(error)")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any],
                    let data = json["punchdetails"] as? [[String: Any]] {
                    //print(data)

                    for datas in data {
                        let lat  = datas["punch_loc_lat"] as! String
                        let long = datas["punch_loc_long"] as! String

                        var annotations = [MKPointAnnotation]()

                        let latitude = CLLocationDegrees(lat)
                        let longitude = CLLocationDegrees(long)
                        let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!)
                        let annotation = MKPointAnnotation()
                        annotation.coordinate = coordinate
                        annotations.append(annotation)


                        self.TheMap.addAnnotations(annotations)
                        self.TheMap.delegate = self

                        self.centerMapOnLocation(location: annotations[0], regionRadius: 2000.0)

                        // Connect all the mappoints using Poly line.

                        var points: [CLLocationCoordinate2D] = [coordinate] //[CLLocationCoordinate2D]()

                        for annotation in annotations {
                            points.append(annotation.coordinate)
                        }

                        print("this is points = \(points)")

                        let polyline = MKPolyline(coordinates: &points, count: points.count)

                        //self.TheMap.add(polyline)

                    } //for loop closed

                }
            } catch {
                print(error)
            }

        }
        task.resume()


    }

}

1 个答案:

答案 0 :(得分:1)

我确定如果您分享了print声明的结果,问题就会很明显。你可能会看到很多印刷品陈述。最后,你应该在for循环中定义 之外的数组,在循环中只定义append个值,然后在循环之后添加折线:

do {
    if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
        let data = json["punchdetails"] as? [[String: Any]] {

        var annotations = [MKPointAnnotation]()

        for datas in data {
            let lat  = datas["punch_loc_lat"] as! String
            let long = datas["punch_loc_long"] as! String

            let latitude = CLLocationDegrees(lat)
            let longitude = CLLocationDegrees(long)
            let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!)
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            annotations.append(annotation)
        }

        self.TheMap.delegate = self  // you really should do this in IB or, if you feel compelled to do it programmatically, in viewDidLoad

        // Connect all the mappoints using Poly line.

        let points = annotations.map { $0.coordinate }

        print("this is points = \(points)")

        let polyline = MKPolyline(coordinates: &points, count: points.count)

        DispatchQueue.main.async {
            self.centerMapOnLocation(location: annotations[0], regionRadius: 2000.0)
            self.TheMap.addAnnotations(annotations)
            self.TheMap.add(polyline)
        }
    }
} catch {
    print(error)
}

注意,我还会从主队列中与地图视图进行所有交互。