I have more than 2000 location pins in SwiftData.
My model like this:
@Model
class HaritaModel {
let id: Int
let sto_title: String
let sto_latitude: Double
let sto_longitude: Double
let sto_address: String
let sto_city: String
let sto_country: String
init(id: Int, sto_title: String, sto_latitude: Double, sto_longitude: Double, sto_address: String, sto_city: String, sto_country: String) {
self.id = id
self.sto_title = sto_title
self.sto_latitude = sto_latitude
self.sto_longitude = sto_longitude
self.sto_address = sto_address
self.sto_city = sto_city
self.sto_country = sto_country
}
}
I want to take the user's location and show them the pins at a certain distance. I want these pins to be dynamically updated when the user pan or zoom the map.
The code I am trying to write is as follows:
//
// HaritaTest.swift
//
import SwiftUI
import MapKit
import SwiftData
struct HaritaTest: View {
@Environment(\.modelContext) private var contextHarita
@Query private var harita: [HaritaModel]
@State private var userPosition: MapCameraPosition = .userLocation(fallback: .automatic)
@State private var userCoordinate: CLLocationCoordinate2D?
var body: some View {
Text("Total Boutique \(harita.count)")
Map(initialPosition: { userPosition }) { haritaView in
ForEach(harita) { point in
if let userCoordinate = userCoordinate,
let stoLatitude = point.sto_latitude,
let stoLongitude = point.sto_longitude,
let latitude = Double(stoLatitude),
let longitude = Double(stoLongitude) {
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
if haritaView.contains(coordinate: coordinate) {
MapPin(coordinate: coordinate)
}
}
}
}
.onAppear {
CLLocationManager().requestWhenInUseAuthorization()
getUserLocation()
}
}
private func getUserLocation() {
if let userLocation = CLLocationManager().location {
userCoordinate = userLocation.coordinate
}
}
}
struct HaritaTest_Previews: PreviewProvider {
static var previews: some View {
HaritaTest()
}
}
can you support me?
thanks in advance