我正在尝试在地图上显示用户的当前位置,但由于某种原因,我没有采用我的默认坐标。
我有一个在UIViewController中调用的MKMapView类。
MapView.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface MapView : MKMapView <MKMapViewDelegate, CLLocationManagerDelegate>{
CLLocationManager *locationManager;
}
@end
MapView.m
#import "MapView.h"
@interface MapView ()
@end
@implementation MapView
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
self.delegate = self;
[self addAnnotation:[self userLocation]];
[locationManager startUpdatingLocation];
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
NSLog(@"didUpdateUserLocation");
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 250, 250);
[self setRegion:[self regionThatFits:region] animated:YES];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate;
point.title = @"Where am I?";
point.subtitle = @"I'm here!!!";
[self addAnnotation:point];
}
- (MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
NSLog(@"viewForAnnotation");
static NSString *identifier = @"MyAnnotation";
if ([annotation isKindOfClass:[MKUserLocation class]]) {
NSLog(@"Is the user %f, %f", [annotation coordinate].latitude, [annotation coordinate].longitude);
return nil;
}
return nil;
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views{
NSLog(@"didAddAnnotationViews");
for (MKAnnotationView *view in views){
if ([[view annotation] isKindOfClass:[MKUserLocation class]]){
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([[view annotation] coordinate] , 250, 250);
[mapView setRegion:region animated:YES];
}
}
}
@end
一旦访问地图,我就会得到以下输出。
viewForAnnotation
Is the user 0.000000, 0.000000
didAddAnnotationViews
我无法理解为什么即使重新提交自定义坐标,我的didUpdateUserLocation:
也永远不会被调用。
我在这里缺少什么?
答案 0 :(得分:0)
您正在使用CLLocationManager
并将其设置为delegate
,但您的委托方法都是MKMapViewDelegate
的方法。
您可以设置mapview的委托,也可以使用locationManager:didUpdateLocations:
CLLocationManagerDelegate
方法。
答案 1 :(得分:0)
如果对您来说重要的是用户可以选择在地图上打开和关闭他的位置,那么Nevan King是正确的。但是,如果您可以继续显示用户位置,则无需编写脚本。只需在故事板中右键单击mapView(在我认为属性中),选中“显示用户位置”框。