我不使用 MapBox 但如果您可以访问该区域的跨度(地图的水平和垂直距离)
您可以从注记的坐标中减去所需的纬度跨度量,并为地图设置该中心。
///Centers the map region by placing the passed annotation in the center of the I quadrant
func centerTop(annotation: SpecialAnnot){
//Find a 4th of the span (The horizontal and vertical span representing the amount of map to display.)
let latCorrection = region.span.latitudeDelta/4 + region.span.latitudeDelta/8
self.region = MKCoordinateRegion(center: .init(latitude: annotation.coordinate.latitude - latCorrection, longitude: annotation.coordinate.longitude), span: region.span)
}
这是一些 SwiftUI 代码。
import SwiftUI
import MapKit
class SpecialAnnot: NSObject, MKAnnotation, Identifiable{
let id: UUID = .init()
var coordinate: CLLocationCoordinate2D
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
super.init()
}
}
struct QuarterCenteredView: View {
@State var region: MKCoordinateRegion = MKCoordinateRegion()
let annotationCoordinate: [SpecialAnnot] = [SpecialAnnot(coordinate: .init(latitude: 40.748817, longitude: -73.985428))]
var body: some View {
VStack{
Button("center quadrant I", action: {
centerTop(annotation: annotationCoordinate.first!)
})
Map(coordinateRegion: $region, annotationItems: annotationCoordinate, annotationContent: { annot in
MapAnnotation(coordinate: annot.coordinate, content: {
Image(systemName: "mappin").foregroundColor(.red)
})
})
.onAppear(perform: {
DispatchQueue.main.async {
region = MKCoordinateRegion(center: annotationCoordinate.first!.coordinate, span: region.span)
}
})
}
}
///Centers the map region by placing the passed annotation in the center of the I quadrant
func centerTop(annotation: SpecialAnnot){
//Find a 4th of the span (The horizontal and vertical span representing the amount of map to display.)
let latCorrection = region.span.latitudeDelta/4 + region.span.latitudeDelta/8
self.region = MKCoordinateRegion(center: .init(latitude: annotation.coordinate.latitude - latCorrection, longitude: annotation.coordinate.longitude), span: region.span)
}
}
struct QuarterCenteredView_Previews: PreviewProvider {
static var previews: some View {
QuarterCenteredView()
}
}