将地图限制为特定范围?

时间:2015-08-16 02:39:47

标签: ios skmaps

有没有办法设置地图边界,实际上限制用户只能在这些边界内平移?

我得到的最接近的是mapView.fitBounds方法,但它似乎并没有限制平移。我做错了什么,或者这种方法不能满足我的需求?

我正在使用SKMaps iOS SDK 2.5版

谢谢!

1 个答案:

答案 0 :(得分:4)

以下是我编写(based on this answer)的一些代码,用于在边界框内绑定用户,由左上角坐标和右下角坐标定义。

在启动mapView对象之后的viewDidLoad中如此

mapView = [[SKMapView alloc] initWithFrame:CGRectMake( 0.0f, 0.0f,  CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) )];

//Setting the zoom limit, (totally optional)
SKMapZoomLimits zoomLimits;
zoomLimits.mapZoomLimitMin = 15.153500;
zoomLimits.mapZoomLimitMax = 21;
mapView.settings.zoomLimits = zoomLimits;

//Creating our bounding box by specifying a top left point, and a bottom right
CLLocationCoordinate2D topLeftBoundary;
topLeftBoundary.longitude = 21.174489;
topLeftBoundary.latitude = 39.777993;

CLLocationCoordinate2D botRightBoundary;
botRightBoundary.longitude = 21.191678;
botRightBoundary.latitude = 39.765834;

_boundaries = [SKBoundingBox boundingBoxWithTopLeftCoordinate:topLeftBoundary bottomRightCoordinate:botRightBoundary];
}

然后我定义isInBoundingBox方法。

-(BOOL) isInBoundingBox: (SKCoordinateRegion)regionBox {
    if (_boundaries.topLeftCoordinate.latitude < regionBox.center.latitude || _boundaries.bottomRightCoordinate.latitude > regionBox.center.latitude ||
    _boundaries.topLeftCoordinate.longitude > regionBox.center.longitude || _boundaries.bottomRightCoordinate.longitude < regionBox.center.longitude)
    {
        return false;    
    }
return true;
}

然后在我们didChangeToRegion方法上执行此操作:

- (void)mapView:(SKMapView*)curMapView didChangeToRegion:(SKCoordinateRegion)region{
    //NSLog(@" @@@@@@@@ did change to ZOOM LEVEL: %f and lat: %f, long: %f",region.zoomLevel, region.center.latitude, region.center.longitude);

    BOOL inBoundingBox = [self isInBoundingBox:region];
    if (inBoundingBox) {
        // if mapRegion is valid save it
        _lastValidRegion = region;
    } else {
        // if mapRegion is invalid reposition the map inside the bounding box
        [mapView setVisibleRegion:_lastValidRegion];
    }
}