SwiftUI Map is not centered around the annotations

Viewed 639

I use below code to load the Map, but after results come, still the map is centered to user location not around the annotation, due to that I have to scroll to the pin to see.

Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: searchResults) { dest in
    MapAnnotation(coordinate: dest.coordinate, anchorPoint: CGPoint(x: 0.5, y: 0.5)) {
            MapPin(coordinate)
    }
}
1 Answers

To change what the map displays, you just need to change the region to which it is binded (coordinateRegion: $region). Changing its center moves the map. To act on the zoom you must act on the span property.

I already suggest you move the card to the first element of your searchResults array :

Map(coordinateRegion: $region, annotationItems: searchResults) {result in
   MapMarker(coordinate: result.coordinate)
}
.onChange(of: searchResults) {newValue in
   if let result = newValue.first {
      region.center = result.coordinate
   }
}

But if you want to move (and zoom in / out) the map so that it encompasses all the results :

Map(coordinateRegion: $region, annotationItems: searchResults) { result in
     MapMarker(coordinate: result.coordinate)
}
.onChange(of: searchResults) { _ in
     if !searchResults.isEmpty {
          region = regionThatFitsTo(coordinates: searchResults.map { $0.coordinate })
     }
}

And the function that calculates the region that fits :

func regionThatFitsTo(coordinates: [CLLocationCoordinate2D]) -> MKCoordinateRegion {
        var topLeftCoord = CLLocationCoordinate2D(latitude: -90, longitude: 180)
        var bottomRightCoord = CLLocationCoordinate2D(latitude: 90, longitude: -180)
        for coordinate in coordinates {
            topLeftCoord.longitude = fmin(topLeftCoord.longitude, coordinate.longitude)
            topLeftCoord.latitude = fmax(topLeftCoord.latitude, coordinate.latitude)
            bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, coordinate.longitude)
            bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, coordinate.latitude)
        }

        var region: MKCoordinateRegion = MKCoordinateRegion()
        region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5
        region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5
        region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.4
        region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.4
        return region
    }
Related