2014-10-17 63 views
0

我試圖在我的MKMapView上放置所有註釋,同時將當前用戶位置保持在地圖中心。在保持用戶居中位置的同時在MKMapView上擬合注釋

關於如何縮小區域以適應地圖上的註釋,已經有很多參考文獻[1] [2],但他們會調整當前的中心位置,例如如果所有註釋位於我當前用戶位置的東邊,則它將進行調整,以便當前用戶位置移動到地圖的左側。

如何縮放我的地圖,使其適合顯示的所有註釋,但保持用戶當前位置在地圖中心?

參考文獻:

[1] Zooming MKMapView to fit annotation pins?

[2] - (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);

+1

嘗試下面的我的方法實現的:獲取到來自用戶的位置的註釋的最大距離然後使用MKCoordinateRegionMakeWithDistance設置集中在用戶的區域緯度/距離爲maximumDistance * 2的位置 – Anna 2014-10-18 11:52:28

+0

這是一個好主意,我昨天也得出了相同的結論,但我不確定'MKCoordinateRegionMakeWithDistance'的變量,因爲他們同時使用了'latitudinalMeters'和'longitudinalMeters '我現在只是設置爲相同的,但我不確定你可以輕鬆完成,我會在幾分鐘後發佈我的方法。「 – 2014-10-18 12:55:58

+0

是的,您可以將兩者作爲相同的值傳遞,地圖視圖將根據視圖的比例和可以顯示的縮放級別自動進行調整。 – Anna 2014-10-18 15:18:34

回答

1

我發現這個解決方案是最可靠的和建議的@Anna它以及所以它可能是一個確定的溶液。

這是我的方法(如遺傳MKMapView

- (void)fitAnnotationsKeepingCenter { 
    CLLocation *centerLocation = [[CLLocation alloc] 
    initWithLatitude:self.centerCoordinate.latitude 
    longitude:self.centerCoordinate.longitude]; 

    // starting distance (do not zoom less than this) 
    CLLocationDistance maxDistance = 350; 

    for (id <MKAnnotation> vehicleAnnotation in [self annotations]) { 
    CLLocation *annotationLocation = [[CLLocation alloc] initWithLatitude:vehicleAnnotation.coordinate.latitude longitude:vehicleAnnotation.coordinate.longitude]; 
    maxDistance = MAX(maxDistance, [centerLocation distanceFromLocation:annotationLocation]); 
    } 

    MKCoordinateRegion fittedRegion = MKCoordinateRegionMakeWithDistance(centerLocation.coordinate, maxDistance * 2, maxDistance * 2); 
    fittedRegion = [self regionThatFits:fittedRegion]; 
    fittedRegion.span.latitudeDelta *= 1.2; 
    fittedRegion.span.longitudeDelta *= 1.2; 

    [self setRegion:fittedRegion animated:YES]; 
}