我有一個類似的問題,獲取基於用戶縮放camera.altitude,以顯示在標籤。
由於沒有像「regionISChangingAnimated」這樣的方法,但只有WillChange和DidChange,我在WillChange啓動了一個計時器,並在DidChange中使其失效。計時器調用一個方法(updateElevationLabel)來計算地圖上方相機的高度。
但是,由於在調用regionDidChange之前不會計算camera.altitude,請使用zoomscale和地圖的起始高度(zoomscale = 1.0並不總是等於altitude = 0m,這取決於您在世界的哪個位置)計算當前的高度。起始高度是下面方法中的一個浮點數,在加載和每個區域更改時設置一次。
最後,您可以更改高度的格式,例如,從公里以外米超過一定的高度(10'000米以下)。
對於老校友:1米=3.2808399英尺
-(void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
if (showsElevation) {
//update starting height for the region
MKMapCamera *camera = map.camera;
CLLocationDistance altitude = camera.altitude;
MKZoomScale currentZoomScale = map.bounds.size.width/map.visibleMapRect.size.width;
float factor = 1.0/currentZoomScale;
startingHeight = altitude/factor;
elevationTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(updateElevationLabel)
userInfo:Nil
repeats:YES];
[elevationTimer fire];
}
}
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
[elevationTimer invalidate];
}
-(void)updateElevationLabel {
//1. create the label
if (!elevationLabel) {
elevationLabel = [UILabel new];
[elevationLabel setFrame:CGRectMake(0, 18, 200, 44)];
[elevationLabel setBackgroundColor:[UIColor redColor]];
[self addSubview:elevationLabel];
}
//2. grab the initial starting height (further updated on region changes)
if (startingHeight == 0) {
MKMapCamera *camera = map.camera;
CLLocationDistance altitude = camera.altitude;
MKZoomScale currentZoomScale = map.bounds.size.width/map.visibleMapRect.size.width;
float factor = 1.0/currentZoomScale;
startingHeight = altitude/factor;
}
//3. get current zoom scale and altitude, format changes
MKZoomScale currentZoomScale = map.bounds.size.width/map.visibleMapRect.size.width;
float altitude = startingHeight * (1/currentZoomScale);
if (altitude>10000) {
altitude = altitude/1000;
[elevationLabel setText:[NSString stringWithFormat:@"%.1fkm", altitude]];
} else {
[elevationLabel setText:[NSString stringWithFormat:@"%.0fm", altitude]];
}
}
相反,文檔說什麼,這種方法不是連續叫,而是一旦當變焦開始在原來的職位說明。 – pixbroker