使用此:
extension MKMapView {
/// when we call this function, we have already added the annotations to the map, and just want all of them to be displayed.
func fitAll() {
var zoomRect = MKMapRectNull;
for annotation in annotations {
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.01, 0.01);
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(100, 100, 100, 100), animated: true)
}
/// we call this function and give it the annotations we want added to the map. we display the annotations if necessary
func fitAll(in annotations: [MKAnnotation], andShow show: Bool) {
var zoomRect:MKMapRect = MKMapRectNull
for annotation in annotations {
let aPoint = MKMapPointForCoordinate(annotation.coordinate)
let rect = MKMapRectMake(aPoint.x, aPoint.y, 0.1, 0.1)
if MKMapRectIsNull(zoomRect) {
zoomRect = rect
} else {
zoomRect = MKMapRectUnion(zoomRect, rect)
}
}
if(show) {
addAnnotations(annotations)
}
setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100), animated: true)
}
}
然後,爲您創造MapView的一個出口,例如map
,之後和大家說明要麼添加到陣列中的所謂annotations
地圖,請訪問上面的方法,如所以:
map.fitAll()
OR
map.fitAll(in:annotations, true)
分別爲。
使用真實或具體取決於您是否收到或不添加註釋到地圖的最後一條語句錯誤...