diff GeoQuiz/Logic/CityGame.swift @ 7:d945e52b0704

implement dynamic map
author Dennis C. M. <dennis@denniscm.com>
date Tue, 04 Oct 2022 18:54:24 +0200
parents 1946bbfde4af
children e09959b4e4a8
line wrap: on
line diff
--- a/GeoQuiz/Logic/CityGame.swift	Thu Sep 29 12:00:17 2022 +0200
+++ b/GeoQuiz/Logic/CityGame.swift	Tue Oct 04 18:54:24 2022 +0200
@@ -7,6 +7,8 @@
 
 import Foundation
 import AVFAudio
+import SwiftUI
+import MapKit
 
 class CityGame: Game, ObservableObject {
     
@@ -16,8 +18,12 @@
     var data: [String: T]
     var dataAsked = [String: T]()
     
-    // Data
-    @Published var correctAnswer = (key: String(), value: T(country: String(), lat: Double(), lon: Double()))
+    @Published var mapImage: UIImage? = nil
+    @Published var correctAnswer = (key: String(), value: T(country: String(), lat: Double(), lon: Double())) {
+        willSet {
+            getMapImage(lat: newValue.value.lat, lon: newValue.value.lon)
+        }
+    }
     
     // User
     @Published var userChoices = [String: T]()
@@ -29,7 +35,7 @@
     // Alerts
     @Published var alertTitle = String()
     @Published var alertMessage = String()
-    @Published var showingNoLivesAlert = false
+    @Published var showingGameOverAlert = false
     @Published var showingEndGameAlert = false
     @Published var showingWrongAnswerAlert = false
     @Published var showingExitGameAlert = false
@@ -38,10 +44,6 @@
     @Published var scoreScaleAmount = 1.0
     @Published var livesScaleAmount = 1.0
     
-    // Modal views
-    @Published var showingBuyLivesView = false
-    @Published var showingGameStatsView = false
-    
     // Sound effects
     @Published var player: AVAudioPlayer?
     
@@ -51,3 +53,35 @@
         askQuestion()
     }
 }
+
+extension CityGame {
+    func getMapImage(lat: Double, lon: Double) {
+        let region = MKCoordinateRegion(
+            center: CLLocationCoordinate2D(
+                latitude: lat,
+                longitude: lon
+            ),
+            span: MKCoordinateSpan(
+                latitudeDelta: 1.0,
+                longitudeDelta: 1.0
+            )
+        )
+
+        // Map options
+        let mapOptions = MKMapSnapshotter.Options()
+        mapOptions.region = region
+        mapOptions.size = CGSize(width: 600, height: 600)
+        mapOptions.showsBuildings = true
+
+        // Create the snapshotter and run it
+        let snapshotter = MKMapSnapshotter(options: mapOptions)
+        snapshotter.start { (snapshot, error) in
+            if let snapshot = snapshot {
+                self.mapImage = snapshot.image
+            } else if let error = error {
+                print(error.localizedDescription)
+            }
+        }
+    }
+}
+