Restrict MKMapView scrolling

后端 未结 6 1556
独厮守ぢ
独厮守ぢ 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条回答
  •  萌比男神i
    2020-11-29 04:22

    In my case, I needed to restrict bounds to tiled overlay which has an upperleft / lowerRight coordinates. Code above still works well, but substituted theOverlay.boundingMapRect for MKMapRect paddedBoundingMapRect

    - (void)mapView:(MKMapView *)_mapView regionDidChangeAnimated:(BOOL)animated
    {
    if (manuallyChangingMapRect) //prevents possible infinite recursion when we call setVisibleMapRect below
        return;     
    
    [self updateDynamicPaddedBounds];
    
    MKMapPoint pt =  MKMapPointForCoordinate( mapView.centerCoordinate);
    
    BOOL mapInsidePaddedBoundingRect = MKMapRectContainsPoint(paddedBoundingMapRect,pt );
    
    if (!mapInsidePaddedBoundingRect)
    {
        // Overlay is no longer visible in the map view.
        // Reset to last "good" map rect...
    
        manuallyChangingMapRect = YES;
        [mapView setVisibleMapRect:lastGoodMapRect animated:YES];
        manuallyChangingMapRect = NO;
    
    
    }
    
    
    -(void)updateDynamicPaddedBounds{
    
    ENTER_METHOD;
    
    CLLocationCoordinate2D  northWestPoint= CLLocationCoordinate2DMake(-33.841171,151.237318 );
    CLLocationCoordinate2D  southEastPoint= CLLocationCoordinate2DMake(-33.846127, 151.245058);
    
    
    
    MKMapPoint upperLeft = MKMapPointForCoordinate(northWestPoint);
    MKMapPoint lowerRight = MKMapPointForCoordinate(southEastPoint);
    double width = lowerRight.x - upperLeft.x;
    double height = lowerRight.y - upperLeft.y;
    
    
    MKMapRect mRect = mapView.visibleMapRect;
    MKMapPoint eastMapPoint = MKMapPointMake(MKMapRectGetMinX(mRect), MKMapRectGetMidY(mRect));
    MKMapPoint westMapPoint = MKMapPointMake(MKMapRectGetMaxX(mRect), MKMapRectGetMidY(mRect));
    MKMapPoint northMapPoint = MKMapPointMake(MKMapRectGetMidX(mRect), MKMapRectGetMaxY(mRect));
    MKMapPoint southMapPoint = MKMapPointMake(MKMapRectGetMidX(mRect), MKMapRectGetMinY(mRect));
    
    double xMidDist = abs(eastMapPoint.x -  westMapPoint.x)/2;
    double yMidDist = abs(northMapPoint.y -  southMapPoint.y)/2;
    
    
    upperLeft.x = upperLeft.x + xMidDist;
    upperLeft.y = upperLeft.y + yMidDist;
    
    
    double paddedWidth =  width - (xMidDist*2); 
    double paddedHeight = height - (yMidDist*2);
    
    paddedBoundingMapRect= MKMapRectMake(upperLeft.x, upperLeft.y, paddedWidth, paddedHeight);
    

    }

提交回复
热议问题