Restrict MKMapView scrolling

后端 未结 6 1547
独厮守ぢ
独厮守ぢ 2020-11-29 03:28

I\'m trying to add a custom image to an MKMapView as an MKOverlayView - I need to restrict users from being able to scroll outside the bounds of th

6条回答
  •  眼角桃花
    2020-11-29 04:31

    Anna's (https://stackoverflow.com/a/4126011/3191130) solution in Swift 3.0, I added to an extension:

    extension HomeViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        if manuallyChangingMapRect {
            return
        }
        guard let overlay = self.mapOverlay else {
            print("Overlay is nil")
            return
        }
        guard let lastMapRect = self.lastGoodMapRect else {
            print("LastGoodMapRect is nil")
            return
        }
    
        let mapContainsOverlay = MKMapRectContainsRect(mapView.visibleMapRect, overlay.boundingMapRect)
        if mapContainsOverlay {
            let widthRatio: Double = overlay.boundingMapRect.size.width / mapView.visibleMapRect.size.width
            let heightRatio: Double = overlay.boundingMapRect.size.height / mapView.visibleMapRect.size.height
            // adjust ratios as needed
            if (widthRatio < 0.9) || (heightRatio < 0.9) {
                manuallyChangingMapRect = true
                mapView.setVisibleMapRect(overlay.boundingMapRect, animated: true)
                manuallyChangingMapRect = false
            }
        } else if !overlay.intersects(mapView.visibleMapRect) {
                // Overlay is no longer visible in the map view.
                // Reset to last "good" map rect...
                manuallyChangingMapRect = true
                mapView.setVisibleMapRect(lastMapRect, animated: true)
                manuallyChangingMapRect = false
            }
            else {
                lastGoodMapRect = mapView.visibleMapRect
        }
    }
    }
    

    To setup the map use this:

    override func viewDidLoad() {
        super.viewDidLoad()
        setupMap()
    }
    
    func setupMap() {
        mapView.delegate = self
        let radius:CLLocationDistance = 1000000
        mapOverlay = MKCircle(center: getCenterCoord(), radius: radius)
        if let mapOverlay = mapOverlay  {
            mapView.add(mapOverlay)
        }
        mapView.setRegion(MKCoordinateRegionMake(getCenterCoord(), getSpan()), animated: true)
        lastGoodMapRect = mapView.visibleMapRect
    }
    
    func getCenterCoord() -> CLLocationCoordinate2D {
        return CLLocationCoordinate2DMake(LAT, LON)
    }
    func getSpan() -> MKCoordinateSpan {
        return MKCoordinateSpanMake(10, 10)
    }
    

提交回复
热议问题