Reputation: 11
This code is working completely fine although when i have lots annotations from different different region, i am not able to set the region of the map so that i can see all annotation on the screen. Thats why some annotations are not visible.
How can we calculate my map region so that each and every annotations can we shown on the screen.
struct MapViewWithAnnotatios: UIViewRepresentable {
var viewModel: MapViewWithAnnotationsViewModel
// Location Manager object to request location updates from the core API
// Annotations array
var annotations: [MKPointAnnotation]?
var mapRegion: MKCoordinateRegion
// @State var mapView: MKMapView?
var mapRegion1: MKCoordinateRegion?
// Setup function for the representable
func setup() {
// Set other properties if needed
}
// Function to configure the representable view
func makeUIView(context: Context) -> MKMapView {
// Call the setup function
setup()
// Initialize the representable view
let mapView = MKMapView(frame: UIScreen.main.bounds)
mapView.delegate = context.coordinator
DispatchQueue.main.async {
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
}
// Provide annotations if they exists
if let annotations = annotations {
mapView.showAnnotations(annotations, animated: true)
}
mapView.setRegion(mapRegion, animated: true)
// Return the representable view
if viewModel.isCircleOverlayNeeded {
let miles = 3.0
let meters = miles * 1609.34
let circle = MKCircle(center: mapView.region.center, radius: meters)
mapView.setVisibleMapRect(circle.boundingMapRect, edgePadding: .init(top: 20, left: 50, bottom: 20, right: 50) ,animated: true)
mapView.addOverlay(circle)
}
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
print("updateUIView")
}
Upvotes: 1
Views: 228
Reputation: 6849
You already have a solution in your code:
if let annotations = annotations {
mapView.showAnnotations(annotations, animated: true)
}
That changes the visible region to show each annotation on the screen.
With the next line, you destroy your solution:
mapView.setRegion(mapRegion, animated: true)
a possible solution would be
if let annotations = annotations {
mapView.showAnnotations(annotations, animated: true)
} else {
mapView.setRegion(mapRegion, animated: true)
}
Upvotes: 0