Setting a MapView's center coordinate does not take into account full size of MapView (off-screen portion)

穿精又带淫゛_ 提交于 2019-12-09 18:46:03

问题


The Problem

I have a view that includes a full-screen MKMapView. The bottom half of the MapView is covered with a TableView that has translucent cells so that the map shows through.

When I center on an annotation coordinate, the current location for example, the annotation view is blocked by the TableView.

- (void)centerOnCurrentLocation
{
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.locationManager.location.coordinate, 50000, 50000);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}

Attempted Solution

I first tried to programmatically shift the map to offset the center, shifting the annotation up. This approach works if I turn off animation, though it's not a simple solution. Nor do I want to turn off animation.

Instead I thought that if I extend the MapView off the top of the screen by the same height as the TableView the center of the MapView would be exactly where I want it. It doesn't work! When I set the center coordinate on the larger MapView the annotation still appears in the center of the screen, not in the center of the larger MapView. It seems like MKMapView is using the view's visible region when calculating its center.

This is what I would expect to see when I center on current location using the enlarged MapView.

If only MKMapView had a centerOffset property that allowed you to shift the center by some CGPoint.

Does anybody have a simple, elegant solution to offset a MapView's center?


回答1:


Just to clarify on my comment, you can use setVisibleMapRect: edgePadding: to create the offset you want. You will need to put it in the mapView delegate method regionDidChangeAnimated: this will fire anytime the region changes on your map so you need to wrap your code with a flag to know when to apply the offset or it can be applied multiple times. Here is what you need to do:

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

    if (!self.mapInsetsSet) {
        self.mapInsetsSet=TRUE;
        [self.myMapView setVisibleMapRect:self.myMapView.visibleMapRect edgePadding:UIEdgeInsetsMake(10, 0, 0, 0) animated:YES];
    }

}

In the above code, mapInsetsSet is just a bool that you can set elsewhere to control when to apply the offset. Also, you will need to adjust the UIEdgeInsetsMake to the desired offset.



来源:https://stackoverflow.com/questions/30218612/setting-a-mapviews-center-coordinate-does-not-take-into-account-full-size-of-ma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!