MKMapView - Limit map scroll to a square overlay

2020-04-12 00:54发布

I have a MKMapView with a square overlay described as:

   CLLocationCoordinate2D coordsBg[5]={
    CLLocationCoordinate2DMake(31.750865,35.180882),
    CLLocationCoordinate2DMake(31.740331,35.180882),
    CLLocationCoordinate2DMake(31.740331,35.165452),
    CLLocationCoordinate2DMake(31.750865,35.165452),
    CLLocationCoordinate2DMake(31.750865,35.180882)
};     

MKPolygon *bg=[MKPolygon polygonWithCoordinates:coordsBg count:5];
[map addOverlay:bg];

I wish to limit the user from scrolling outside of the overlay.

Can I limit the MKMapView scroll view for that? Or there is an other method?

Thanks

Shani

1条回答
【Aperson】
2楼-- · 2020-04-12 01:01

After Few hours of banging my head, I got to this solution that work great for me.

It mixes up :

This post: set the zoom level of an mkmapview

And This link: restrict mkmapview scrolling from @Anna Karenina comment to my question.

And This is my code:

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    lastGoodMapRect = mapView.visibleMapRect;
    lastGoodRegion = mapView.region;
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{

    if (manuallyChangingMapRect) {
        manuallyChangingMapRect=NO;
        return;
    }

    if( [mapView zoomLevel] > 16 )
    {
        [mapView setCenterCoordinate:lastGoodRegion.center zoomLevel:16 animated:YES];
    }

    MKMapRect visibleRect = mapView.visibleMapRect;
    MKMapRect OverlayRect = bg.boundingMapRect;
    MKMapRect intersectionRect = MKMapRectIntersection(visibleRect,OverlayRect);

    //you can change the min and max zoom off course
    if(!MKMapRectEqualToRect(visibleRect,intersectionRect)){
        if( [mapView zoomLevel] < 15){

            [mapView setCenterCoordinate:lastGoodRegion.center zoomLevel:15 animated:YES];
        }else if( [mapView zoomLevel] > 16 )
        {
            [mapView setCenterCoordinate:lastGoodRegion.center zoomLevel:16 animated:YES];
        }else{
            manuallyChangingMapRect=YES;
            [mapView setVisibleMapRect:lastGoodMapRect animated:YES];
        }
    }

}
查看更多
登录 后发表回答