2016-09-29 8 views
0

Я создаю своеобразное приложение направления/GPS, и до сих пор все было просто.MKPolyLine не отображается в приложении iOS в Swift 2.0

  • Я понял, как найти местоположение пользователя (с их разрешения, конечно)
  • Я сумел дать им возможность установить пункт назначения в быстрый легкий способ

Однако , Я столкнулся с небольшой проблемой. Я хочу, чтобы пользователь мог выбрать место назначения на экране, и приложение предоставит им самый быстрый способ приехать туда.

Вот мой ViewController:

class ViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate { 

    @IBOutlet var mapOfMaps: MKMapView! 
    let locationManager = CLLocationManager() 
    var center:CLLocationCoordinate2D! 
    var SourcePM:MKPlacemark! 
    let sourcePlacemark: MKPlacemark! = nil 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.locationManager.delegate = self 
     self.locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     self.locationManager.requestWhenInUseAuthorization() 
     self.locationManager.startUpdatingLocation() 
     self.mapOfMaps.showsUserLocation = true 

     let sourceAnnotation = MKPointAnnotation() 

     if let location = locationManager.location { 
      sourceAnnotation.coordinate = location.coordinate 
     } 
     let longPress = UILongPressGestureRecognizer(target: self, action: #selector(CardioViewController.action(_:))) 
     longPress.minimumPressDuration = 1.0 
     mapOfMaps.addGestureRecognizer(longPress) 

     //directionRequest 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     let location = locations.last 
     center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) 
     let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.003, longitudeDelta: 0.003)) 
     self.mapOfMaps.setRegion(region, animated: true) 
     self.locationManager.stopUpdatingLocation() 
     SourcePM = MKPlacemark(coordinate: center, addressDictionary: nil) 
    } 
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { 
     print("ERROr " + error.localizedDescription) 
    } 

    func action(gestureRecognizer:UIGestureRecognizer) { 
     let touchPoint = gestureRecognizer.locationInView(self.mapOfMaps) 
     let newCoord:CLLocationCoordinate2D = mapOfMaps.convertPoint(touchPoint, toCoordinateFromView: self.mapOfMaps) 

     let newAnotation = MKPointAnnotation() 
     newAnotation.coordinate = newCoord 
     newAnotation.title = "Your Destination" 
     mapOfMaps.addAnnotation(newAnotation) 
     let anotPM = MKPlacemark(coordinate: newAnotation.coordinate, addressDictionary: nil) 


     let source = MKMapItem(placemark: SourcePM) 
     let dstn = MKMapItem(placemark: anotPM) 

     let directionRequest = MKDirectionsRequest() 
     directionRequest.source = source 
     directionRequest.destination = dstn 
     directionRequest.transportType = .Automobile 

     // Calculate the direction 
     let directions = MKDirections(request: directionRequest) 

     // 8. 
     directions.calculateDirectionsWithCompletionHandler() { 
      (response, error) in 
      if(error == nil && response != nil) { 
       for route in response!.routes { 
        var r: MKRoute = route as! MKRoute 
        self.mapOfMaps.addOverlay(r.polyline, level: MKOverlayLevel.AboveRoads) 
       } 
      } 

      let route = response!.routes[0] 
      self.mapOfMaps.addOverlay((route.polyline), level: MKOverlayLevel.AboveLabels) 


      let rect = route.polyline.boundingMapRect 
      self.mapOfMaps.setRegion(MKCoordinateRegionForMapRect(rect), animated: true) 
     } 

    } 
    func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { 
     let renderer = MKPolylineRenderer(overlay: overlay) 
     renderer.strokeColor = UIColor.orangeColor() 
     renderer.alpha = 1 
     renderer.lineWidth = 4.0 

     return renderer 
    } 
} 

, чтобы помочь вам через мой код. Мой пользователь будет нажимать и удерживать место назначения на карте, и приложение добавит аннотацию, и оно должно быть отправлено должно быть. Тем не менее, все, что происходит, - это аннотация, добавленная к карте, и карта будет настраиваться так, чтобы показывать как местоположения (местоположение пользователя и местоположение аннотации), но не маршрут.

ответ

0

Возможно, это не идеальное решение, но стоит отметить, что обе функции locationManager не могут работать одновременно. Я пробовал комментировать одну из функций locationManager, и низкий уровень, и другие отлично работали.