iOS init MKMapView具有用户位置和适当的比例/跨度

时间:2013-12-05 10:03:19

标签: ios mkmapview

我这样初始化我的mapviewControler:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.firstShow=TRUE;
    self.mapView.delegate=self;
    self.mapView.showsUserLocation=YES;
    self.cllmng=[[CLLocationManager alloc]init];
    self.cllmng.delegate=self;
    self.cllmng.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;
    self.cllmng.distanceFilter=50;
    [self.cllmng startUpdatingLocation];
}

我让mapviewControler实现CLLocationManagerDelegate,并在我的代码中实现- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

我遇到的问题是我想以适当的比例初始化以当前用户位置为中心的地图视图。我打算通过

来做到这一点
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation * currentLoci=[locations lastObject];
MKCoordinateRegion r;
MKCoordinateSpan span;
span.latitudeDelta = 1;
span.longitudeDelta = 1;
r.span = span;
CLLocationCoordinate2D c;
c.longitude=currentLoci.coordinate.longitude;
c.latitude=currentLoci.coordinate.latitude;
r.center = c;
[self.mapView setRegion:r animated:YES];
}

有时,在 - (void)viewDidload中调用[self.cllmng startUpdatingLocation]后,我无法立即调用- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations。因此,地图视图只是初始化显示用户位置,但显示整个澳大利亚。如何在地图视图的初始化中设置比例/跨度,甚至不会触发didUpdateLocations? THX!

2 个答案:

答案 0 :(得分:4)

您可以使用CLLocation管理器自行修改区域,只需设置mapView的trackingMode,它就会自动居中并放大您的位置。如果用户开始拖动地图,则可以禁用跟踪模式,但如果您确实希望他们无法控制,则可以禁用用户交互。这是怎么做的

[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];

参考:https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html#//apple_ref/occ/instm/MKMapView/setUserTrackingMode:animated

答案 1 :(得分:0)

iOS 11.x Swift 4.0 Craigs回答,更新。

mapView.showsUserLocation = true

我担心不那么明显。