2015-05-12 31 views
0

我想在mapview中的多個座標之間添加疊加路徑。我嘗試了像下面的代碼,但它顯示了「不能調用'map'類型的參數列表((CLLocation) - > CLLocationCoordinate2D)」的錯誤。請讓我知道我該如何解決這個問題?如何在MKMapView中添加疊加路徑swift

我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

答案是有用的,但請注意,你甚至都不需要首先創建CLLocations的數組,然後將它們映射到CLLocationCoordinate2Ds的數組。你可以直接創建一個CLLocationCoordinate2D數組:'var coordinates = [location1,location2]'。也不需要重複座標值 - 使用已有值(變量1,變量2)的變量。 – Anna

+0

次要細節:region2中心正在使用location1而不是location2。但是,您不需要執行setRegion在某個位置添加註釋。在這裏,只有第二個setRegion調用對顯示有影響。 – Anna

回答

2

這應該工作:

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

一行代碼:

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

與您的代碼的問題是,locations是可變鍵入[CLLocation!](注意這裏有感嘆號),但是你宣佈它的ele在封閉發言:爲CLLocation(不!):

(location: CLLocation) -> CLLocationCoordinate2D