2017-03-02 273 views
1

我正在嘗試創建一個應用程序,其功能之一是在用戶移動時繪製線條。爲什麼MKPolyline沒有顯示在我的應用程序中?

這裏是類

class traceuserViewController: UIViewController,CLLocationManagerDelegate, MKMapViewDelegate { 
     var locationManager = CLLocationManager() 
     var startLocation: CLLocation? 
     var endLocation: CLLocation? 
     @IBOutlet weak var mapView: MKMapView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     locationManager.delegate = self 
     self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
     self.locationManager.distanceFilter = 30.0 
     self.locationManager.startMonitoringSignificantLocationChanges() 
     self.locationManager.startUpdatingLocation() 
     mapView.showsUserLocation = true 
     mapView.mapType = .hybrid 
     self.mapView.delegate = self 
} 
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    //user's current location 
    let nowlocation = locations.last 
    userLocations.append(nowlocation!) 

    print("HERE IS THE LOCATION ARRAY") 
    print(userLocations) 

    //show the current location region 
    let center = CLLocationCoordinate2D(latitude: nowlocation!.coordinate.latitude, longitude: nowlocation!.coordinate.longitude) 
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.7, longitudeDelta: 0.7)) 
    self.mapView.setRegion(region, animated: true) 
    drawRoute(locationArray: userLocations) 
} 
    func drawRoute(locationArray: [CLLocation]) { 
    if (locationArray.count) > 1 { 
     var destinationLocIndex = (locationArray.count) - 1 
     var startLocIndex = (locationArray.count) - 2 

     let destinationloc = locationArray[destinationLocIndex].coordinate 
     let startLoc = locationArray[startLocIndex].coordinate 

     var routeArray = [startLoc, destinationloc] 
     //test if the function works well or not 
     print(routeArray) 
     var geodesicLine = MKGeodesicPolyline(coordinates: routeArray , count: routeArray.count) 
     mapView.add(geodesicLine, level: .aboveRoads) 

    } 
} 

//draw in the mapview 
private func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer! { 
    if overlay is MKPolyline{ 
     let polylineRenderer = MKPolylineRenderer(overlay: overlay) 
     polylineRenderer.strokeColor = UIColor.blue 
     polylineRenderer.lineWidth = 5.0 
     return polylineRenderer 
    }else{ 
     os_log("Failed to draw the polyline", log: OSLog.default, type: .debug) 
     return nil 
    } 
} 

多次嘗試後,我仍然不知道爲什麼它不畫,當用戶移動地圖上的路線,任何人都可以請我有我一些提示?

歡呼

回答

0

我推斷你使用的斯威夫特3從代碼片段(例如中didUpdateLocations簽名;使用.hybrid而非雨燕2.3的.Hybrid;等等)。

但是,mapView(_:rendererFor:)的簽名不正確。在斯威夫特3,它是:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { 
    ... 
} 

如果你曾經有沒有出現工作委託方法,它添加一個斷點,可以確認,如果這就是所謂的全部或沒有(如果是稱爲,你可以通過它並進一步診斷問題)。

+0

是的,它現在正在工作!非常感謝:P – Jenny

相關問題