如何在MKMapView swift中添加叠加路径

时间:2015-05-12 10:13:31

标签: ios swift mkmapview mkoverlay coordinate

我想在mapview中的多个坐标中添加叠加路径。我尝试了下面的代码,但它显示错误"无法调用' map'使用类型的参数列表((CLLocation) - > CLLocationCoordinate2D)"。请让我知道如何解决这个问题?

我的ViewController.swift文件

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate{
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //For Location 1
        let location1 = CLLocationCoordinate2D(
            latitude: 51.481188400000010000,
            longitude: -0.190209099999947280
        )

        let annotation1 = MKPointAnnotation()
        annotation1.coordinate = location1;
        annotation1.title = "Chelsea"
        annotation1.subtitle = "Chelsea"

        let span = MKCoordinateSpanMake(0.15, 0.15)

        let region1 = MKCoordinateRegion(center: location1, span: span)
        mapView.setRegion(region1, animated: true)
        mapView.addAnnotation(annotation1)

        //For Location 2
        let location2 = CLLocationCoordinate2D(
            latitude: 51.554947700000010000,
            longitude: -0.108558899999934510
        )

        let annotation2 = MKPointAnnotation()
        annotation2.coordinate = location2;
        annotation2.title = "Arsenal"
        annotation2.subtitle = "Arsenal"

        let region2 = MKCoordinateRegion(center: location1, span: span)
        mapView.setRegion(region2, animated: true)
        mapView.addAnnotation(annotation2)

        var locations = [CLLocation(latitude: 51.481188400000010000, longitude: -0.190209099999947280), CLLocation(latitude: 51.554947700000010000,longitude:  -0.108558899999934510)]

        //This line shows error
        var coordinates = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate})

        var polyline = MKPolyline(coordinates: &coordinates, count: locations.count)

        mapView.addOverlay(polyline)
    }

    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        if overlay is MKPolyline {
            var polylineRenderer = MKPolylineRenderer(overlay: overlay)
            polylineRenderer.strokeColor = UIColor.blueColor()
            polylineRenderer.lineWidth = 5
            return polylineRenderer
        }

        return nil
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:2)

这应该有效:

var coordinates = locations.map {
    location in
    return location.coordinate
}

一衬垫:

var coordinates = locations.map { $0.coordinate }

您的代码存在的问题是locations[CLLocation!]类型的变量(请注意此处的感叹号),但您要将其元素声明为CLLocation(不带!)在封闭中:

(location: CLLocation) -> CLLocationCoordinate2D