Zoom to fit current location and annotation on map

MKMapRectUnion computes and returns a new rect, nothing more. You need to tell the mapView to set its visible area to that new rect:

myMapView.setVisibleMapRect(zoomRect, animated: true)

self.mapView.showAnnotations(self.mapView.annotations, animated: true)

Use below MKMapView extension-

extension MKMapView
{
    func fitAllMarkers(shouldIncludeCurrentLocation: Bool) {

        if !shouldIncludeCurrentLocation
        {
            showAnnotations(annotations, animated: true)
        }
        else
        {
            var zoomRect = MKMapRectNull

            let point = MKMapPointForCoordinate(userLocation.coordinate)
            let pointRect = MKMapRectMake(point.x, point.y, 0, 0)
            zoomRect = MKMapRectUnion(zoomRect, pointRect)

            for annotation in annotations {

                let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
                let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0)

                if (MKMapRectIsNull(zoomRect)) {
                    zoomRect = pointRect
                } else {
                    zoomRect = MKMapRectUnion(zoomRect, pointRect)
                }
            }

            setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(8, 8, 8, 8), animated: true)
        }
    }
}

Tags:

Swift

Mapkit