I'm trying to draw a route using MapKit and SwiftUI and then have a MapItem aka (Marker) that I can see is intersecting with the route.
I tried using creating an MKCircle for my MapPoint that I want to avoid and then tested the boundingMapRect of the MKCircle testing against the boundingMapRect of the route's polyline. The issue that I am having is that the polyline of the route is creating a MapRect that is the size of my visible map and therefore it's always showing an intersecting point.
Below is my sample code
import SwiftUI
import MapKit
struct ContentView: View {
@State private var selectedResult: MKMapItem?
@State private var route: [MKRoute]?
@State var intersection: Bool = false
private let startingPoint = CLLocationCoordinate2D(
latitude: 40.83657722488077,
longitude: 14.306896671048852
)
private let destinationCoordinates = CLLocationCoordinate2D(
latitude: 40.849761,
longitude: 14.263364
)
private let testPoint = CLLocationCoordinate2D(
latitude: 40.84013,
longitude: 14.29389
)
var locations = [CLLocationCoordinate2D]()
var body: some View {
Map(selection: $selectedResult) {
// Adding the marker for the starting point
Marker("Start", coordinate: self.startingPoint)
.tint(.green)
Marker("End", coordinate: destinationCoordinates)
.tint(.green)
Marker("Low Bridge", systemImage: "x.circle.fill", coordinate: testPoint)
// Show the route if it is available
MapCircle(center: testPoint, radius: 0.01)
.foregroundStyle(.cyan.opacity(0.5))
.mapOverlayLevel(level: .aboveRoads)
if (route?.count ?? 0 > 0) {
ForEach (route!, id: \.self) { r in
MapPolyline(r)
.stroke(.blue, lineWidth: 5)
}
}
}
.onChange(of: intersection) {
print(intersection)
}
.onChange(of: selectedResult){
getDirections()
}
.onAppear {
self.selectedResult = MKMapItem(placemark: MKPlacemark(coordinate: self.destinationCoordinates))
}
}
func getDirections() {
self.route = []
// Check if there is a selected result
guard let selectedResult else { return }
// Create and configure the request
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: self.startingPoint))
request.destination = self.selectedResult
request.transportType = .walking
request.requestsAlternateRoutes = false
// Get the directions based on the request
Task {
let directions = MKDirections(request: request)
let response = try? await directions.calculate()
route = response?.routes
if (route?.count ?? 0 > 0) {
route?.forEach() { r in
print(r.name)
let lb = MKCircle(center: testPoint, radius: 0.0001)
if (lb.boundingMapRect.intersects(r.polyline.boundingMapRect))==true {
print(lb.boundingMapRect)
print(r.polyline.boundingMapRect)
print("Intersect")
} else {
print("Clear")
}
}
}
}
}
}