AutoCat/AutoCat/Controllers/EventsController.swift
2020-09-06 13:14:47 +03:00

69 lines
2.4 KiB
Swift

import UIKit
import MapKit
class EventPin: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
class EventsController: UIViewController {
@IBOutlet weak var map: MKMapView!
public var events: [VehicleEvent] = [] {
didSet {
self.pins = self.events.map { event in
let coordinate = CLLocationCoordinate2D(latitude: event.latitude, longitude: event.longitude)
let subtitle = event.address ?? "\(event.latitude), \(event.longitude)"
let date = Date(timeIntervalSince1970: event.date)
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
let title = formatter.string(from: date)
return EventPin(coordinate: coordinate, title: title, subtitle: subtitle)
}
}
}
private var pins: [EventPin] = []
override func viewDidLoad() {
super.viewDidLoad()
#if targetEnvironment(macCatalyst)
self.map.showsZoomControls = true
#endif
self.map.addAnnotations(self.pins)
self.centerMap()
}
func centerMap() {
var minLat = 0.0, maxLat = 0.0, minLon = 0.0, maxLon = 0.0
for event in self.events {
if event.latitude < minLat || minLat == 0 { minLat = event.latitude }
if event.latitude > maxLat || maxLat == 0 { maxLat = event.latitude }
if event.longitude < minLon || minLon == 0 { minLon = event.longitude }
if event.longitude > maxLon || maxLon == 0 { maxLon = event.longitude }
}
let center = CLLocationCoordinate2D(latitude: (minLat + maxLat)/2, longitude: (minLon + maxLon)/2)
let leftTop = CLLocation(latitude: minLat, longitude: minLon)
let rightBottom = CLLocation(latitude: maxLat, longitude: maxLon)
var diagonal = leftTop.distance(from: rightBottom)
if diagonal < 1000 {
diagonal = 1000
}
let region = MKCoordinateRegion(center: center, latitudinalMeters: diagonal, longitudinalMeters: diagonal)
self.map.setRegion(region, animated: true)
}
}