MKMapView Region

857 views Asked by At

I have a question regarding setting the region on my MKMapView.

I need to set the mapview to display a specific region when my view first loads.

The north east and south west latitude and longitude of this region is:

North East Coordinate Lat:59.623724 Long:2.911587
South West Coordinate Lat:49.004833 Long:-11.361825

Further to this, I would like to 'lock' the mapview to this region. Ideally the lock will be transparent, i.e: the coordinates above represent the maximum extent of the MKMapView. However if it is simply a case of checking the northeast and southwest coordinates within

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

and resetting the view if they exceed my maximum range, that would be acceptable to me also.

Many thanks for any pointers on this matter.

EDIT: Regarding the first part of my question, I have figured out I can set the initial region on the MKMapView using the following code:

CLLocationCoordinate2D neCoord;
neCoord.latitude = 59.787643;
neCoord.longitude = 3.025857;

CLLocationCoordinate2D swCoord;
swCoord.latitude = 49.394171;
swCoord.longitude = -11.036642;
MKCoordinateRegion region;
region.center.latitude = neCoord.latitude - (neCoord.latitude - swCoord.latitude) * 0.5;
region.center.longitude = neCoord.longitude + (swCoord.longitude - neCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(neCoord.latitude - swCoord.latitude); // Add a little extra space on the sides
region.span.longitudeDelta = fabs(swCoord.longitude - neCoord.longitude); // Add a little extra space on the sides

region = [self.mapView regionThatFits:region];
[self.mapView setRegion:region animated:YES];
1

There are 1 answers

1
RyanR On

First, you'll need to make sure you set the region on the map view after the view has been displayed. If you set it before the map has loaded, it probably won't center on that region. Once you've done that, just set self.mapView.zoomEnabled = NO; and self.mapView.scrollEnabled = NO; and it will prevent the user from moving the map around.

If you want to lock the maximum bounds the user can view but still allow scrolling and zooming, you will have to use -mapView:regionDidChangeAnimated: and 'bump' the user back inside your bounds if they leave it. Note that the user experience for this will probably suck - they'll pan around, let go, and then the map will suddenly move back to the region you defined. You could try using -mapView:regionWillChangeAnimated: and modify the map region if they left your boundaries, that could be a little less jarring.