AutoCat/AutoCat/Controllers/Location/GlobalEventsController.swift

87 lines
2.7 KiB
Swift

import UIKit
import MapKit
import PKHUD
import AutoCatCore
class EventPin: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
var id: String
init(id: String, coordinate: CLLocationCoordinate2D, title: String?, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
self.id = id
}
convenience init(event: VehicleEventDto) {
let coordinate = CLLocationCoordinate2D(latitude: event.latitude, longitude: event.longitude)
let address = event.address ?? "\(event.latitude), \(event.longitude)"
let date = Date(timeIntervalSince1970: event.date)
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
let dateStr = formatter.string(from: date)
if let number = event.number {
self.init(id: event.id, coordinate: coordinate, title: number, subtitle: dateStr)
} else {
self.init(id: event.id, coordinate: coordinate, title: dateStr, subtitle: address)
}
}
}
class GlobalEventsController: UIViewController {
var map: MKMapView!
var filter: Filter!
override func viewDidLoad() {
super.viewDidLoad()
map = MKMapView()
map.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(map)
NSLayoutConstraint.activate([
map.leadingAnchor.constraint(equalTo: view.leadingAnchor),
map.trailingAnchor.constraint(equalTo: view.trailingAnchor),
map.topAnchor.constraint(equalTo: view.topAnchor),
map.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
#if targetEnvironment(macCatalyst)
if #available(OSX 11.0, *) {
self.map.showsCompass = true
}
self.map.showsZoomControls = true
#endif
Task { await loadEvents() }
}
func loadEvents() async {
do {
HUD.show(.progress)
let events = try await ApiService.shared.events(with: self.filter)
self.title = String.localizedStringWithFormat(NSLocalizedString("events found", comment: ""), events.count)
let pins = events.map(EventPin.init(event:))
self.map.removeAnnotations(self.map.annotations)
self.map.addAnnotations(pins)
self.map.centerOnPins()
HUD.hide()
} catch {
HUD.show(error: error)
}
}
@IBAction func close(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
}