2017-03-02 112 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

相关问题