matthew
matthew

Reputation: 477

Problems with MKMapView on first use

I have an MKMapView but when the user logs on the first time and allows location services, it doesn't show there location. If they leave the view and come back, it works. I am using what is listed bellow to solve the problem. It solves the problem but then the user can no longer zoom because when there location is updated, it takes them back to the specified location. How would I fix the first problem while making scrolling work.

Here is what I am using:

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    MKUserLocation *myLocation = [self.schoolMap userLocation];
    CLLocationCoordinate2D coord = [[myLocation location] coordinate];
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 9000, 9000);
    [self.schoolMap setRegion:region animated:NO];
}

Upvotes: 0

Views: 138

Answers (2)

Stéphane de Luca
Stéphane de Luca

Reputation: 13621

It is possible that you did not received user's location by the time you set the region. There's a way to handle this situation by letting the mapView shows the user's location whenever it got to as follows:

 CLLocation *location = [[self.schoolMap userLocation] location];
 bool hasLocation = location!=nil;

 if (!hasLocation) {
     [self.mapView showsUserLocation];
 } else {
     CLLocationCoordinate2D zoomLocation = location.coordinate;
     MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 2000, 2000);
     [self.mapView setRegion:viewRegion animated:NO];

Note that this does not demand you update the location on a regular basis.

Upvotes: 0

matt
matt

Reputation: 535915

Do not use location manager at all. Just tell the map view to track the user's location. Then implement this delegate method:

- (void)mapView:(MKMapView *)mapView
        didUpdateUserLocation:(MKUserLocation *)userLocation {
    CLLocationCoordinate2D coordinate = userLocation.location.coordinate;
    MKCoordinateRegion reg =
        MKCoordinateRegionMakeWithDistance(coordinate, 600, 600);
    mapView.region = reg;
}

Now, that will keep trying to set the map every time the user moves, so if you don't want that, add a BOOL switch so that you only do this the first time (when the map first gets the user location).

Upvotes: 1

Related Questions