4
votes

I'm trying to set a custom starting region in an iOS app using MKMapView's setRegion. The app runs fine, and a map appears, but no matter what I try I can't get the region to change. I've tried many tutorials and solutions, but none are working. Here's my code:

-(void)viewDidAppear:(BOOL)animated{
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta  = 0.001;
    span.longitudeDelta = 0.001;

    region.span = span;
    region.center.latitude = 100;
    region.center.longitude = 100;

    [mapView setRegion:(region) animated:(TRUE)];
}

I have the MKMapView and Core Location frameworks added to the projects properly, I import MapKit.h, and I declare mapView, so I don't know why it's not working.

Thank you,

Jacob

2
BOOL values are YES and NO, so TRUE is not what you should be using here. Why do you have the variables in brackets? Also, make use of the helper functions MKCoordinateSpanMake and MKCoordinateRegionMake. - Adam Eberbach
@AdamEberbach I've implemented your suggestions, but it's still not working. Here's the new code: -(void)viewDidAppear:(BOOL)animated{ MKCoordinateRegion region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(26, 80), MKCoordinateSpanMake(0.001, 0.001)); [mapView setRegion:region animated:YES]; } - jspiegel

2 Answers

3
votes

It sounds like the map view's IBOutlet is not connected to the map view control in the xib/storyboard.

If it's not connected, the mapView variable will be nil and calling methods on it will do nothing.

In the xib/storyboard, right-click on View Controller and connect the mapView outlet to the map view control.



delegate


Another separate point:
In your first code example, you are setting the region's center to 100, 100. Please note that this is an invalid coordinate. If the map view was actually connected, setting the center to this would have caused a crash with "Invalid Region". Latitude must be from -90 to +90 (longitude must be from -180 to +180).

By the way, the new coordinate you're trying in the code posted in the comment (26, 80) is in India. Since you're setting the span to a relatively small value, you'll need to zoom out a lot to see this.

1
votes

However it was set as answered, I will let here an example of what worked for me, when I had no clue why setRegion was not working at all. In my case the problem was the I've initiated the MKMapView without a frame, e.g.:

override func viewDidLoad() {
  ...
  self.mapView = MKMapView() // Wrong!
  ...
  self.mapView.setRegion(...) // Does not work!
}

It looks like that the whole region thing is calculated with regards the the initial (CGRect). It worked for me by doing:

override func viewDidLoad() {
  ...
  self.mapView = MKMapView(frame: CGRect(0, 108, self.mapView.bounds.width, self.mapView.bounds.height))
  self.mapView.setRegion(...) // Oh, it works!
}

This problem was described here too.