Frage

I implemented the following MKMapView method, which runs after annotations are added. I have my MKMapView map (parishMap) set to "Shows user location" in Interface Builder, and upon loading the mapview, the blue dot always appears within a second or so on the mapview.

Here's the code I have in my Map View controller implementation:

// Center map on user location (initially)
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    for(MKAnnotationView *annotationView in views) {
        if(annotationView.annotation == parishMap.userLocation) {
            MKCoordinateRegion region;
            MKCoordinateSpan span;

            span.latitudeDelta=0.03;
            span.longitudeDelta=0.03;

            CLLocationCoordinate2D location=parishMap.userLocation.coordinate;

            location = parishMap.userLocation.location.coordinate;

            region.span=span;
            region.center=location;

            [parishMap setRegion:region animated:TRUE];
            [parishMap regionThatFits:region];
        }
    }
}

When I open the mapview on my iPhone 4, the mapview always (and almost immediately) moves to center on the userLocation dot. However, when I open the mapview on an iPhone 3Gs or iPod Touch (2010), it doesn't center on the userLocation, but just stays at the default zoom/region I set for the map view.

Any ideas as to why this code won't work for non-iPhone 4 devices (they're all running 4.2.x latest iOS)?

War es hilfreich?

Lösung

This is probably an issue with the amount of time it takes for the GPS to lock a position on these different devices.

I'd recommend using CLLocationManager and its delegate methods to center the map.

You can start updating location by creating an instance of CLLocationManager, setting its delegate property to self and then implementing:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

Where you can center your map accordingly based on the latest location update.

Andere Tipps

have you tried using this code to center the map:

[mapView setCenterCoordinate:location animated:YES];

I'm not sure why it would work for iPhone 4 and not the others, but this is the code I use to adjust the region:

    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(location, 0.03, 0.03);
    MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];

    [mapView setRegion:adjustedRegion animated:YES];

Try it that way and see how that works. The way you're doing the regionThatFits method, that's actually not supposed to be how the method is used. You can try commenting out that last line of your code, it should make no difference. Anyway, try it with the method I just gave and let me know if you have any questions.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top