-
-
Save hishnash/2ffc9fca47f80f41684361da02435556 to your computer and use it in GitHub Desktop.
EarthquakeHeatMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Charts | |
| import Observation | |
| import SwiftUI | |
| struct EarthquakeHeatMap: View { | |
| @Environment(EarthquakeMapModel.self) private var model | |
| var body: some View { | |
| let data = model.data | |
| Chart { | |
| HexCellsPlot(cells: data.cells) | |
| .symbolSize(by: .value("Cell size", 1)) | |
| Coastline(points: data.coastline) | |
| } | |
| .chartXScale(domain: data.xDomain, range: .plotDimension(padding: 0)) | |
| .chartYScale(domain: data.yDomain, range: .plotDimension(padding: 0)) | |
| .chartXAxis(.hidden) | |
| .chartYAxis(.hidden) | |
| .chartLegend(.hidden) | |
| .chartForegroundStyleScale( | |
| domain: 0...data.maximumEarthquakeCount, | |
| range: HeatMapStyle.frequencyGradient, | |
| type: .symmetricLog(slopeAtZero: 1) | |
| ) | |
| .modifier(HexagonSizeModifier(xDomain: data.xDomain, radius: data.hexRadius)) | |
| .aspectRatio(data.aspectRatio, contentMode: .fit) | |
| } | |
| } | |
| struct HexagonSizeModifier: ViewModifier { | |
| // Keeping geometry-driven state here lets resizing update the size scale | |
| // without making the chart content depend on the measured plot size. | |
| let xDomain: ClosedRange<Double> | |
| let radius: Double | |
| @State private var symbolArea: CGFloat = 18 | |
| func body(content: Content) -> some View { | |
| content | |
| .chartSymbolSizeScale(domain: 0...1, range: 0...symbolArea) | |
| .chartPlotStyle { plot in | |
| plot.onGeometryChange(for: CGFloat.self) { geometry in | |
| let width = geometry.size.width | |
| / (xDomain.upperBound - xDomain.lowerBound) | |
| * radius * sqrt(3) | |
| return max(18, width * width * 0.92) | |
| } action: { symbolArea = $0 } | |
| } | |
| } | |
| } | |
| @MainActor | |
| @Observable | |
| final class EarthquakeMapModel { | |
| let data: PreparedEarthquakeMapData | |
| init(data: PreparedEarthquakeMapData) { | |
| self.data = data | |
| } | |
| } | |
| struct HexCellsPlot: ChartContent { | |
| let cells: [HexCell] | |
| var body: some ChartContent { | |
| PointPlot( | |
| cells, | |
| x: .value("Longitude", \HexCell.longitude), | |
| y: .value("Latitude", \HexCell.latitude) | |
| ) | |
| .foregroundStyle( | |
| by: .value("Earthquake frequency", \HexCell.earthquakeCount) | |
| ) | |
| .accessibilityLabel(\HexCell.accessibilityLabel) | |
| .accessibilityValue(\HexCell.accessibilityValue) | |
| .symbol(Hexagon()) | |
| } | |
| } | |
| struct Coastline: ChartContent { | |
| let points: [CoastlinePoint] | |
| var body: some ChartContent { | |
| LinePlot( | |
| points, | |
| x: .value("Longitude", \.longitude), | |
| y: .value("Latitude", \.latitude), | |
| series: .value("Coastline segment", \.segment) | |
| ) | |
| .lineStyle(StrokeStyle(lineWidth: 1.5, lineJoin: .round)) | |
| .foregroundStyle(.background) | |
| .accessibilityHidden(true) | |
| } | |
| } | |
| struct Hexagon: ChartSymbolShape { | |
| var perceptualUnitRect: CGRect { | |
| CGRect(x: 0.067, y: 0, width: 0.866, height: 1) | |
| } | |
| func path(in rect: CGRect) -> Path { | |
| let points = [ | |
| CGPoint(x: rect.midX, y: rect.minY), | |
| CGPoint(x: rect.maxX, y: rect.minY + rect.height * 0.25), | |
| CGPoint(x: rect.maxX, y: rect.minY + rect.height * 0.75), | |
| CGPoint(x: rect.midX, y: rect.maxY), | |
| CGPoint(x: rect.minX, y: rect.minY + rect.height * 0.75), | |
| CGPoint(x: rect.minX, y: rect.minY + rect.height * 0.25) | |
| ] | |
| var path = Path() | |
| path.addLines(points) | |
| path.closeSubpath() | |
| return path | |
| } | |
| } | |
| enum HeatMapStyle { | |
| static let frequencyGradient = Gradient(colors: [ | |
| Color(red: 0.11, green: 0.22, blue: 0.34).opacity(0.12), | |
| Color(red: 0.10, green: 0.55, blue: 0.58), | |
| Color(red: 0.98, green: 0.72, blue: 0.24), | |
| Color(red: 0.88, green: 0.22, blue: 0.18) | |
| ]) | |
| static func symbolArea( | |
| in size: CGSize, | |
| data: PreparedEarthquakeMapData | |
| ) -> CGFloat { | |
| let renderedWidth = size.width | |
| / (data.xDomain.upperBound - data.xDomain.lowerBound) | |
| * data.hexRadius * sqrt(3) | |
| return max(18, renderedWidth * renderedWidth * 0.92) | |
| } | |
| } | |
| struct PreparedEarthquakeMapData: Sendable { | |
| let earthquakes: [Earthquake] | |
| let coastline: [CoastlinePoint] | |
| let cells: [HexCell] | |
| let cellsByID: [HexCell.ID: HexCell] | |
| let xDomain: ClosedRange<Double> | |
| let yDomain: ClosedRange<Double> | |
| let hexRadius: Double | |
| let maximumEarthquakeCount: Int | |
| var aspectRatio: CGFloat { | |
| (xDomain.upperBound - xDomain.lowerBound) | |
| / (yDomain.upperBound - yDomain.lowerBound) | |
| } | |
| static func load(resourceDirectory: URL? = nil) throws -> Self { | |
| let earthquakes = try Earthquake.load(resourceDirectory: resourceDirectory) | |
| let coastline = try CoastlinePoint.load(resourceDirectory: resourceDirectory) | |
| let hexRadius = 0.3 | |
| let xDomain = 164.0...180.0 | |
| let yDomain = -48.5...(-33.5) | |
| let cells = HexGrid.makeCells(from: earthquakes, radius: hexRadius) | |
| return Self( | |
| earthquakes: earthquakes, | |
| coastline: coastline, | |
| cells: cells, | |
| cellsByID: Dictionary(uniqueKeysWithValues: cells.map { ($0.id, $0) }), | |
| xDomain: xDomain, | |
| yDomain: yDomain, | |
| hexRadius: hexRadius, | |
| maximumEarthquakeCount: cells.map(\.earthquakeCount).max() ?? 1 | |
| ) | |
| } | |
| } | |
| struct HexCell: Identifiable, Sendable { | |
| struct ID: Hashable, Sendable { | |
| let q: Int | |
| let r: Int | |
| } | |
| let id: ID | |
| let longitude: Double | |
| let latitude: Double | |
| let earthquakes: [Earthquake] | |
| var earthquakeCount: Int { earthquakes.count } | |
| var maximumMagnitude: Double { earthquakes.map(\.magnitude).max() ?? 0 } | |
| var accessibilityLabel: String { | |
| return "Grid cell centered at \(abs(latitude).formatted(.number.precision(.fractionLength(1)))) degrees south, \(longitude.formatted(.number.precision(.fractionLength(1)))) degrees east" | |
| } | |
| var accessibilityValue: String { | |
| "\(earthquakeCount.formatted()) earthquakes, maximum magnitude \(maximumMagnitude.formatted(.number.precision(.fractionLength(1))))" | |
| } | |
| } | |
| enum HexGrid { | |
| static func makeCells(from earthquakes: [Earthquake], radius: Double) -> [HexCell] { | |
| Dictionary(grouping: earthquakes) { | |
| cell(x: $0.longitude, y: $0.latitude, radius: radius) | |
| } | |
| .map { id, earthquakes in | |
| let center = center(for: id, radius: radius) | |
| return HexCell( | |
| id: id, | |
| longitude: center.x, | |
| latitude: center.y, | |
| earthquakes: earthquakes | |
| ) | |
| } | |
| .sorted { ($0.id.r, $0.id.q) < ($1.id.r, $1.id.q) } | |
| } | |
| static func cell(x: Double, y: Double, radius: Double) -> HexCell.ID { | |
| rounded( | |
| q: (sqrt(3) / 3 * x - y / 3) / radius, | |
| r: (2 * y / 3) / radius | |
| ) | |
| } | |
| static func center(for id: HexCell.ID, radius: Double) -> (x: Double, y: Double) { | |
| ( | |
| radius * sqrt(3) * (Double(id.q) + Double(id.r) / 2), | |
| radius * 1.5 * Double(id.r) | |
| ) | |
| } | |
| private static func rounded(q: Double, r: Double) -> HexCell.ID { | |
| let x = q | |
| let z = r | |
| let y = -x - z | |
| var roundedX = x.rounded() | |
| var roundedY = y.rounded() | |
| var roundedZ = z.rounded() | |
| let xDifference = abs(roundedX - x) | |
| let yDifference = abs(roundedY - y) | |
| let zDifference = abs(roundedZ - z) | |
| if xDifference > yDifference, xDifference > zDifference { | |
| roundedX = -roundedY - roundedZ | |
| } else if yDifference > zDifference { | |
| roundedY = -roundedX - roundedZ | |
| } else { | |
| roundedZ = -roundedX - roundedY | |
| } | |
| return HexCell.ID(q: Int(roundedX), r: Int(roundedZ)) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment