Advertisement
Guest User

Untitled

a guest
Dec 11th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 9.09 KB | None | 0 0
  1. class MapViewController: UIViewController {
  2.    
  3.     @IBOutlet weak var mapView: MKMapView!
  4.     var route: MKRoute!
  5.     var latestLocation: CLLocation?
  6.     let locationDelegate = LocationDelegate()
  7.     let destination: CLLocation = CLLocation(latitude: 40.851652, longitude: 14.268238)//40.851652, 14.268238
  8.    
  9.     var isCalculateButtonTapped: Bool = false
  10.    
  11.     var stepMaxDistance: Double = 100000
  12.    
  13.     @IBOutlet weak var stattBuonLabel: UILabel!
  14.     //    @IBOutlet weak var embViewCompass: UIView!
  15. //    @IBOutlet weak var imageViewCompass: UIImageView!
  16. //    @IBOutlet weak var txtDistance: UILabel!
  17. //    @IBOutlet weak var btnCalculate: UIButton!
  18. //    @IBOutlet weak var txtWalkingDistance: UILabel!
  19.    
  20.     @IBOutlet weak var btnCompass: UIButton!
  21.    
  22.    
  23.     var yourLocationBearing: CGFloat { return latestLocation?.bearingToLocationRadian(self.yourLocation) ?? 0 }
  24.     var yourLocation: CLLocation {
  25.         get { return UserDefaults.standard.currentLocation }
  26.         set { UserDefaults.standard.currentLocation = newValue }
  27.     }
  28.    
  29.     let locationManager: CLLocationManager = {
  30.         $0.requestWhenInUseAuthorization()
  31.         $0.desiredAccuracy = kCLLocationAccuracyBestForNavigation
  32.         $0.startUpdatingLocation()
  33.         $0.startUpdatingHeading()
  34.         return $0
  35.     }(CLLocationManager())
  36.    
  37.     private func orientationAdjustment() -> CGFloat {
  38.         let isFaceDown: Bool = {
  39.             switch UIDevice.current.orientation {
  40.             case .faceDown: return true
  41.             default: return false
  42.             }
  43.         }()
  44.        
  45.         let adjAngle: CGFloat = {
  46.             switch UIApplication.shared.statusBarOrientation {
  47.             case .landscapeLeft:  return 90
  48.             case .landscapeRight: return -90
  49.             case .portrait, .unknown: return 0
  50.             case .portraitUpsideDown: return isFaceDown ? 180 : -180
  51.             }
  52.         }()
  53.         return adjAngle
  54.     }
  55.    
  56.     override func viewDidLoad() {
  57.        
  58.         super.viewDidLoad()
  59.        
  60.        
  61.         mapView.delegate = self
  62.         // Do any additional setup after loading the view, typically from a nib.
  63.         mapView.showsUserLocation = true
  64.         mapView.userTrackingMode = .followWithHeading
  65.        
  66. //        self.MapViewController.childContaining(CompassViewController)
  67. //        print(self.children.count)
  68.        
  69.         locationManager.delegate = locationDelegate
  70.        
  71.         locationDelegate.locationCallback = { location in
  72.             self.latestLocation = location
  73.            
  74. //            vedere se questo codice centra la posizione
  75. //            let region = MKCoordinateRegion(center:
  76. //                CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude),
  77. //                                            span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
  78.            
  79. //            self.mapView.setRegion(region, animated: false) // con animated true, centra la posizione corrente
  80.            
  81.             // calcola la distanza aerea tra due coordinate
  82.             let distance = self.destination.distance(from: location)
  83. //            self.txtDistance.text = "\(distance.magnitude)"//distance.description
  84.             if self.isCalculateButtonTapped {
  85.                 let stepNumber = self.route.steps.count - 1
  86.                 var nearestStep = 0
  87.                 for stepIndex in nearestStep...stepNumber {
  88.                     if (self.route.steps[stepIndex].distance < self.route.steps[nearestStep].distance) {
  89.                         nearestStep = stepIndex
  90.                     }
  91.                 }
  92.                 self.stattBuonLabel.text = "step \(nearestStep) dista: \(self.route.steps[nearestStep].distance)"
  93.             }
  94.         }
  95.        
  96.         locationDelegate.headingCallback = { newHeading in
  97.            
  98.             func computeNewAngle(with newAngle: CGFloat) -> CGFloat {
  99.                 let heading: CGFloat = {
  100.                     let originalHeading = self.yourLocationBearing - newAngle.degreesToRadians
  101.                     switch UIDevice.current.orientation {
  102.                     case .faceDown: return -originalHeading
  103.                     default: return originalHeading
  104.                     }
  105.                 }()
  106.                
  107.                 return CGFloat(self.orientationAdjustment().degreesToRadians + heading)
  108.             }
  109.            
  110.             UIView.animate(withDuration: 0.5) {
  111.                 let angle = computeNewAngle(with: CGFloat(newHeading))
  112. //                self.imageViewCompass.transform = CGAffineTransform(rotationAngle: angle)
  113.             }
  114.         }
  115.     }
  116.    
  117.     @IBAction func onClickCompass(_ sender: Any) {
  118.         let popOverVC = UIStoryboard(name: "MapLayers", bundle: nil).instantiateViewController(withIdentifier: "sbSettings") as! SettingsViewController
  119.         self.addChild(popOverVC)
  120.         popOverVC.view.frame = self.view.frame
  121.         self.view.addSubview(popOverVC.view)
  122.         popOverVC.didMove(toParent: self)
  123.        
  124.     }
  125.    
  126.    
  127.     // funzione che si occupa di ruotare l'immagine in ase alla localizzazione
  128.     //    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
  129.     //        UIView.animate(withDuration: 0.5) {
  130.     //
  131.     //            let angle = newHeading.trueHeading.degreesToRadians // convert from degrees to radians
  132.     //
  133.     //            func computeNewAngle(with newAngle: CGFloat) -> CGFloat {
  134.     //                let heading: CGFloat = {
  135.     //                    let originalHeading = self.yourLocationBearing - newAngle.degreesToRadians
  136.     //                    switch UIDevice.current.orientation {
  137.     //                    case .faceDown: return -originalHeading
  138.     //                    default: return originalHeading
  139.     //                    }
  140.     //                }()
  141.     //
  142.     //                return CGFloat(self.orientationAdjustment().degreesToRadians + heading)
  143.     //            }
  144.     //
  145.     //            UIView.animate(withDuration: 0.5) {
  146.     //                let angle = computeNewAngle(with: CGFloat(newHeading))
  147.     //                self.imageView.transform = CGAffineTransform(rotationAngle: angle)
  148.     //            }
  149.     //
  150.     //        }
  151.     //    }
  152.    
  153.     // da testare
  154.     func getDistanceToDestination(srcMapItem srcmapItem: MKMapItem, destMapItem destmapItem: MKMapItem) {
  155. //        self.embViewCompass
  156.         let request = MKDirections.Request() //create a direction request object
  157.         request.source = srcmapItem //this is the source location mapItem object
  158.         request.destination = destmapItem //this is the destination location mapItem object
  159.         request.transportType = MKDirectionsTransportType.walking //define the transportation method
  160.        
  161.         let directions = MKDirections(request: request) //request directions
  162.         directions.calculate { (response, error) in
  163.             guard let response = response else {
  164.                 print(error.debugDescription)
  165.                 return
  166.             }
  167.             self.route = response.routes[0] //get the routes, could be multiple routes in the routes[] array but usually [0] is the best route
  168. //            self.txtWalkingDistance.text = self.route.distance.description
  169.             self.mapView.addOverlay((self.route.polyline), level: MKOverlayLevel.aboveRoads)
  170.             let rect = self.route.polyline.boundingMapRect
  171.             self.mapView.setRegion(MKCoordinateRegion(rect), animated: true)
  172.         }
  173.        
  174.     }
  175.    
  176.     func calculateDistance(){
  177.         guard let userLocation = latestLocation else { return }
  178.         let myCoordinates = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude ?? 40.833399, longitude: userLocation.coordinate.longitude ?? 14.201540)
  179.         let myPlacemark = MKPlacemark(coordinate: myCoordinates)
  180.         let myMapItem = MKMapItem(placemark: myPlacemark)
  181.        
  182.         let myCoordinates2 = CLLocationCoordinate2D(latitude: destination.coordinate.latitude, longitude: destination.coordinate.longitude)
  183.         let myPlacemark2 = MKPlacemark(coordinate: myCoordinates2)
  184.         let myMapItem2 = MKMapItem(placemark: myPlacemark2)
  185.        
  186.         yourLocation = destination
  187.         self.getDistanceToDestination(srcMapItem: myMapItem, destMapItem: myMapItem2)
  188.     }
  189.    
  190.    
  191.     @IBAction func onClickCalculate(_ sender: Any) {
  192.         isCalculateButtonTapped = true
  193.         calculateDistance()
  194.         // casa 40.833399, 14.201540
  195.        
  196.     }
  197.    
  198. }
  199.  
  200. extension MapViewController: MapViewControllerDelegate, MKMapViewDelegate {
  201.     func update(location: CLLocation) {
  202.         yourLocation = location
  203.     }
  204.    
  205.     func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
  206.         let renderer = MKPolylineRenderer(overlay: overlay)
  207.        
  208.         renderer.strokeColor = .blue
  209.         renderer.lineWidth = 10.0
  210. //        let locationMapPoint = MKMapPoint((latestLocation?.coordinate)!)
  211. //        let locationCGPoint = renderer.point(for: locationMapPoint)
  212.         return renderer
  213.     }
  214.    
  215. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement