Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import CoreLocation
- import Foundation
- import NotificationCenter
- struct Hospital {
- let lat: Double
- let long: Double
- let name: String
- let distance: Double
- let address: String
- let tags: [String]
- }
- var hospitals = [Hospital]()
- var myIndex:Int = 0
- var selectedPlaceInAnotherViewXD = selectedPlace
- var placeValue = "Hospital"
- var rowInOtherView = 0;
- class ViewController: UIViewController, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource {
- @IBOutlet weak var placeTypePickerButton: UIButton!
- var buttonToChange:UIButton = UIButton()
- @IBOutlet weak var radiusLabel: UILabel!
- @IBOutlet weak var radiusSlider: UISlider!
- @IBOutlet weak var table: UITableView!
- @IBOutlet weak var locateMeButton: UIButton!
- let locationManager:CLLocationManager = CLLocationManager()
- let googleAPIUrl:String = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
- let APIKey:String = "AIzaSyBpMA5wLvKdtSl0Cv76VmxoYvvRn6mLCn4"
- var radius = 1500
- var wasDataFetched:Bool = false
- let session = URLSession.shared
- var userLat:Double = 0
- var userLong:Double = 0
- let decoder = JSONDecoder()
- override func viewWillAppear(_ animated: Bool) {
- placeTypePickerButton.titleLabel!.text = placeValue
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- locationManager.delegate = self
- table.isHidden = true
- table.dataSource = self
- table.delegate = self
- table.reloadData()
- sliderToRadius(value: radiusSlider!.value)
- locationManager.requestWhenInUseAuthorization()
- locationManager.startUpdatingLocation()
- locationManager.distanceFilter = 100
- NotificationCenter.default.addObserver(self, selector: #selector(refreshTitle(_:)), name: .didValueChange, object: nil)
- }
- @objc func refreshTitle (_ notification:Notification) {
- placeTypePickerButton.setTitle(selectedPlace, for: .normal)
- }
- @IBAction func onSliderChange(_ sender: Any) {
- sliderToRadius(value: radiusSlider!.value)
- }
- func sliderToRadius(value: Float) {
- let maxDistance:Double = 5.0
- var finalString = ""
- var initVal:Double = Double(value) * maxDistance
- radius = Int(round(initVal*1000))
- if initVal < 1.0 {
- finalString = "\(radius) m"
- } else {
- finalString = "\(round(10*initVal)/10) km"
- }
- radiusLabel.text = finalString
- }
- @IBAction func locateMeButtonPressed(_ sender: Any) {
- wasDataFetched = false
- fetchNearbyPlacesData(long: userLong, lat: userLat)
- }
- func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
- for currentLocation in locations {
- userLat = currentLocation.coordinate.latitude
- userLong = currentLocation.coordinate.longitude
- }
- }
- func fetchNearbyPlacesData(long: Double, lat: Double) {
- hospitals.removeAll()
- let URLLocation = "\(googleAPIUrl)?location=\(lat),\(long)"
- let URLRadius = "\(URLLocation)&radius=\(radius)"
- var URLType:String
- if (selectedPlace.isEmpty) {
- URLType = "\(URLRadius)&types=\(placeValue)"
- } else {
- URLType = "\(URLRadius)&types=\(selectedPlace.lowercased().replacingOccurrences(of: " ", with: "_"))"
- }
- let finalURL:String = "\(URLType)&key=\(APIKey)"
- print(finalURL)
- guard let url = URL(string: finalURL) else {return}
- let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
- guard let dataResponse = data,
- error == nil else {
- print(error?.localizedDescription ?? "Response Error")
- return }
- do{
- let jsonResponse = try JSONSerialization.jsonObject(with:
- dataResponse, options: []) as! [String: Any]
- if let results = jsonResponse["results"] as? [[String: AnyObject]] {
- for result in results {
- var name:String = ""
- var address:String = ""
- var distance:Double = 0.0
- var long:Double = 0.0
- var lat:Double = 0.0
- var tags:[String] = []
- name = result["name"]! as! String
- if let vicinity = result["vicinity"] {
- address = vicinity as! String
- }
- if let types = result["types"] as? [String] {
- tags = types
- }
- if let geometry = result["geometry"] as? [String: AnyObject] {
- if let location = geometry["location"] as? [String: AnyObject] {
- long = location["lng"]! as! Double
- lat = location["lat"]! as! Double
- distance = self.calculateDistance(long1: location["lng"]! as! Double, lat1: location["lat"]! as! Double, long2: self.userLong, lat2: self.userLat)
- }
- }
- hospitals.append(Hospital(lat: lat, long: long, name: name, distance: distance, address: address, tags: tags))
- }
- hospitals.sort { (hos1, hos2) in
- return hos1.distance < hos2.distance
- }
- print(hospitals.count)
- DispatchQueue.main.async {
- self.table.isHidden = false
- self.table.reloadData()
- }
- for hospital in hospitals {
- print(hospital)
- }
- }
- } catch let parsingError {
- print("Error", parsingError)
- }
- }
- wasDataFetched = true
- task.resume()
- }
- func calculateDistance(long1: Double, lat1: Double, long2: Double, lat2: Double) -> Double {
- let R:Float = 6371e3
- let radLat1 = deg2rad(lat1)
- let radLat2 = deg2rad(lat2)
- let phi = deg2rad(lat2-lat1)
- let lambda = deg2rad(long1-long2)
- let a = sin(phi/2) * sin(phi/2) + cos(radLat1) * cos(radLat2) * sin(lambda/2) * sin(lambda/2)
- let c = 2 * atan2(sqrt(a), sqrt(1-a))
- let d:Float = R * Float(c)
- return Double(d)
- }
- func deg2rad(_ number: Double) -> Double {
- return number * .pi / 180
- }
- func numberOfSectionsInTableView(tableView: UITableView) -> Int {
- return 1
- }
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- print("SELF", hospitals.count)
- print("NIE SELF", hospitals.count)
- return hospitals.count
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- print("WYWOLALEM SIE XD")
- let myCell = tableView.dequeueReusableCell(withIdentifier: "hospitalTableCell", for: indexPath) as! HospitalTableCell
- let item = hospitals[indexPath.item]
- myCell.cellAddress.text = item.address
- myCell.cellTitle.text = item.name
- myCell.cellTags.text = item.tags.joined(separator: ", ")
- myCell.cellDistance.text = String(round(item.distance)) + " m"
- print(item)
- return myCell
- }
- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- myIndex = indexPath.row
- print("MY INDEX =>", myIndex)
- performSegue(withIdentifier: "segue", sender: self)
- }
- }
- extension Notification.Name {
- static let didValueChange = Notification.Name("didValueChange")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement