Advertisement
Guest User

Untitled

a guest
Nov 19th, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 8.39 KB | None | 0 0
  1. import UIKit
  2. import CoreLocation
  3. import Foundation
  4. import NotificationCenter
  5.  
  6. struct Hospital {
  7.     let lat: Double
  8.     let long: Double
  9.     let name: String
  10.     let distance: Double
  11.     let address: String
  12.     let tags: [String]
  13. }
  14.  
  15. var hospitals = [Hospital]()
  16. var myIndex:Int = 0
  17. var selectedPlaceInAnotherViewXD = selectedPlace
  18. var placeValue = "Hospital"
  19. var rowInOtherView = 0;
  20.  
  21. class ViewController: UIViewController, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource {
  22.    
  23.     @IBOutlet weak var placeTypePickerButton: UIButton!
  24.     var buttonToChange:UIButton = UIButton()
  25.     @IBOutlet weak var radiusLabel: UILabel!
  26.     @IBOutlet weak var radiusSlider: UISlider!
  27.     @IBOutlet weak var table: UITableView!
  28.     @IBOutlet weak var locateMeButton: UIButton!
  29.     let locationManager:CLLocationManager = CLLocationManager()
  30.     let googleAPIUrl:String = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
  31.     let APIKey:String = "AIzaSyBpMA5wLvKdtSl0Cv76VmxoYvvRn6mLCn4"
  32.     var radius = 1500
  33.     var wasDataFetched:Bool = false
  34.     let session = URLSession.shared
  35.     var userLat:Double = 0
  36.     var userLong:Double = 0
  37.     let decoder = JSONDecoder()
  38.    
  39.     override func viewWillAppear(_ animated: Bool) {
  40.         placeTypePickerButton.titleLabel!.text = placeValue
  41.     }
  42.    
  43.     override func viewDidLoad() {
  44.         super.viewDidLoad()
  45.         locationManager.delegate = self
  46.         table.isHidden = true
  47.         table.dataSource = self
  48.         table.delegate = self
  49.         table.reloadData()
  50.         sliderToRadius(value: radiusSlider!.value)
  51.         locationManager.requestWhenInUseAuthorization()
  52.         locationManager.startUpdatingLocation()
  53.         locationManager.distanceFilter = 100
  54.         NotificationCenter.default.addObserver(self, selector: #selector(refreshTitle(_:)), name: .didValueChange, object: nil)
  55.     }
  56.    
  57.     @objc func refreshTitle (_ notification:Notification) {
  58.         placeTypePickerButton.setTitle(selectedPlace, for: .normal)
  59.     }
  60.    
  61.     @IBAction func onSliderChange(_ sender: Any) {
  62.         sliderToRadius(value: radiusSlider!.value)
  63.     }
  64.    
  65.     func sliderToRadius(value: Float) {
  66.         let maxDistance:Double = 5.0
  67.         var finalString = ""
  68.         var initVal:Double = Double(value) * maxDistance
  69.         radius = Int(round(initVal*1000))
  70.  
  71.         if initVal < 1.0 {
  72.             finalString = "\(radius) m"
  73.         } else {
  74.             finalString = "\(round(10*initVal)/10) km"
  75.         }
  76.        
  77.        
  78.         radiusLabel.text = finalString
  79.     }
  80.    
  81.     @IBAction func locateMeButtonPressed(_ sender: Any) {
  82.         wasDataFetched = false
  83.         fetchNearbyPlacesData(long: userLong, lat: userLat)
  84.     }
  85.    
  86.     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  87.         for currentLocation in locations {
  88.             userLat = currentLocation.coordinate.latitude
  89.             userLong = currentLocation.coordinate.longitude
  90.         }
  91.     }
  92.    
  93.     func fetchNearbyPlacesData(long: Double, lat: Double) {
  94.             hospitals.removeAll()
  95.             let URLLocation = "\(googleAPIUrl)?location=\(lat),\(long)"
  96.             let URLRadius = "\(URLLocation)&radius=\(radius)"
  97.             var URLType:String
  98.             if (selectedPlace.isEmpty) {
  99.                 URLType = "\(URLRadius)&types=\(placeValue)"
  100.             } else {
  101.                
  102.                
  103.                 URLType = "\(URLRadius)&types=\(selectedPlace.lowercased().replacingOccurrences(of: " ", with: "_"))"
  104.             }
  105.             let finalURL:String = "\(URLType)&key=\(APIKey)"
  106.             print(finalURL)
  107.             guard let url = URL(string: finalURL) else {return}
  108.             let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
  109.             guard let dataResponse = data,
  110.                       error == nil else {
  111.                       print(error?.localizedDescription ?? "Response Error")
  112.                       return }
  113.                 do{
  114.                     let jsonResponse = try JSONSerialization.jsonObject(with:
  115.                         dataResponse, options: []) as! [String: Any]
  116.                    
  117.                     if let results = jsonResponse["results"] as? [[String: AnyObject]] {
  118.                         for result in results {
  119.                             var name:String = ""
  120.                             var address:String = ""
  121.                             var distance:Double = 0.0
  122.                             var long:Double = 0.0
  123.                             var lat:Double = 0.0
  124.                             var tags:[String] = []
  125.                            
  126.                             name = result["name"]! as! String
  127.                            
  128.                             if let vicinity = result["vicinity"] {
  129.                                 address = vicinity as! String
  130.                             }
  131.                            
  132.                             if let types = result["types"] as? [String] {
  133.                                 tags = types
  134.                             }
  135.                            
  136.                             if let geometry = result["geometry"] as? [String: AnyObject] {
  137.                                 if let location = geometry["location"] as? [String: AnyObject] {
  138.                                     long = location["lng"]! as! Double
  139.                                     lat = location["lat"]! as! Double
  140.                                     distance = self.calculateDistance(long1: location["lng"]! as! Double, lat1: location["lat"]! as! Double, long2: self.userLong, lat2: self.userLat)
  141.                                 }
  142.                             }
  143.                             hospitals.append(Hospital(lat: lat, long: long, name: name, distance: distance, address: address, tags: tags))
  144.                         }
  145.                         hospitals.sort { (hos1, hos2) in
  146.                             return hos1.distance < hos2.distance
  147.                         }
  148.                         print(hospitals.count)
  149.                         DispatchQueue.main.async {
  150.                             self.table.isHidden = false
  151.                             self.table.reloadData()
  152.                         }
  153.                         for hospital in hospitals {
  154.                             print(hospital)
  155.                         }
  156.                     }
  157.                  } catch let parsingError {
  158.                     print("Error", parsingError)
  159.                }
  160.             }
  161.             wasDataFetched = true
  162.             task.resume()
  163.     }
  164.    
  165.     func calculateDistance(long1: Double, lat1: Double, long2: Double, lat2: Double) -> Double {
  166.         let R:Float = 6371e3
  167.         let radLat1 = deg2rad(lat1)
  168.         let radLat2 = deg2rad(lat2)
  169.         let phi = deg2rad(lat2-lat1)
  170.         let lambda = deg2rad(long1-long2)
  171.         let a = sin(phi/2) * sin(phi/2) + cos(radLat1) * cos(radLat2) * sin(lambda/2) * sin(lambda/2)
  172.         let c = 2 * atan2(sqrt(a), sqrt(1-a))
  173.         let d:Float = R * Float(c)
  174.         return Double(d)
  175.     }
  176.    
  177.     func deg2rad(_ number: Double) -> Double {
  178.         return number * .pi / 180
  179.     }
  180.    
  181.     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
  182.         return 1
  183.     }
  184.    
  185.     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  186.         print("SELF", hospitals.count)
  187.         print("NIE SELF", hospitals.count)
  188.         return hospitals.count
  189.      }
  190.  
  191.     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  192.          print("WYWOLALEM SIE XD")
  193.          let myCell = tableView.dequeueReusableCell(withIdentifier: "hospitalTableCell", for: indexPath) as! HospitalTableCell
  194.          let item = hospitals[indexPath.item]
  195.          myCell.cellAddress.text = item.address
  196.          myCell.cellTitle.text = item.name
  197.          myCell.cellTags.text =  item.tags.joined(separator: ", ")
  198.          myCell.cellDistance.text = String(round(item.distance)) + " m"
  199.          print(item)
  200.          return myCell
  201.      }
  202.    
  203.     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  204.         myIndex = indexPath.row
  205.         print("MY INDEX =>", myIndex)
  206.         performSegue(withIdentifier: "segue", sender: self)
  207.  
  208.     }
  209.        
  210. }
  211.  
  212. extension Notification.Name {
  213.     static let didValueChange = Notification.Name("didValueChange")
  214. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement