问题
I've been getting into mapkit and corelocation for ios. I'm just trying to display a map and zoom in on my current location for now. I can draw the map, with my location. I can get my current location. I just can't get the location data into the map method. I'm a bit of a noob, but thought I knew what I was doing up until this point! :) Any help is appreciated. My code is here, which sort of works but plonks me in the middle of the Atlantic at 0 long and 0 lat!
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
[locationManager setPurpose:@"What use is a nav app if it doesn't know where you are?!?"];
[locationManager setDelegate:self ];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
[locationManager setDistanceFilter:10];
[locationManager startUpdatingLocation];
mapView=[[MKMapView alloc] initWithFrame:self.view.bounds];
[self.view insertSubview:mapView atIndex:0];
mapView.showsUserLocation = TRUE;
mapView.mapType = MKMapTypeStandard;
MKCoordinateSpan span;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;
CLLocationCoordinate2D location = mapView.userLocation.coordinate;
MKCoordinateRegion region;
region.span=span;
region.center=location;
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
[self.view insertSubview:mapView atIndex:0];
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
CLLocationCoordinate2D here = newLocation.coordinate;
NSLog(@"%f %f", here.latitude, here.longitude);
[locationManager stopUpdatingLocation];
}
回答1:
The map view userLocation
will not usually be available right after setting showsUserLocation
to YES.
Implement the map view's delegate methods didUpdateUserLocation
and didFailToLocateUserWithError
. You'll need to set the map view's delegate
property or they won't get called. Change the map's region or center in the didUpdateUserLocation
method--not in viewDidLoad.
Or, set the region in the CLLocationManager's didUpdateToLocation
which you've implemented. Does it get called? Also implement its didFailWithError
method and see if it gets called.
You only need to use either showsUserLocation or the CLLocationManager, not both, to get the current location if you're using MKMapView. But to get the blue marble, you need to use showsUserLocation.
Also, why are you doing insertSubview twice on mapView?
来源:https://stackoverflow.com/questions/7141794/stuck-with-objc-and-mapkit-corelocation