2016-09-28 72 views
1

我基本上有一張地圖,我添加了兩個註釋,它們按預期顯示。MapView顯示所有註釋並儘可能放大地圖

然後I'm使用下面的代碼:

let annotations = [start, end] 
mapView?.showAnnotations(annotations, animated: false) 

而這種放大顯示我有圖有兩個註解,但地圖可以被放大更多,並顯示更詳細的地圖視圖。

This is what I get todaythis is the expected result我想要的。

正如你所看到的,地圖可以放大很多。

任何想法如何實現這一目標?

回答

1

使用此:

extension MKMapView { 
    /// when we call this function, we have already added the annotations to the map, and just want all of them to be displayed. 
    func fitAll() { 
     var zoomRect   = MKMapRectNull; 
     for annotation in annotations { 
      let annotationPoint = MKMapPointForCoordinate(annotation.coordinate) 
      let pointRect  = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.01, 0.01); 
      zoomRect   = MKMapRectUnion(zoomRect, pointRect); 
     } 
     setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(100, 100, 100, 100), animated: true) 
    } 

    /// we call this function and give it the annotations we want added to the map. we display the annotations if necessary 
    func fitAll(in annotations: [MKAnnotation], andShow show: Bool) { 
     var zoomRect:MKMapRect = MKMapRectNull 

     for annotation in annotations { 
      let aPoint   = MKMapPointForCoordinate(annotation.coordinate) 
      let rect   = MKMapRectMake(aPoint.x, aPoint.y, 0.1, 0.1) 

      if MKMapRectIsNull(zoomRect) { 
       zoomRect = rect 
      } else { 
       zoomRect = MKMapRectUnion(zoomRect, rect) 
      } 
     } 
     if(show) { 
      addAnnotations(annotations) 
     } 
     setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100), animated: true) 
    } 

} 

然後,爲您創造MapView的一個出口,例如map,之後和大家說明要麼添加到陣列中的所謂annotations地圖,請訪問上面的方法,如所以:

map.fitAll() 

OR

map.fitAll(in:annotations, true) 

分別爲

使用真實或具體取決於您是否收到或不添加註釋到地圖的最後一條語句錯誤...

1

在斯威夫特:

self.mapView.showAnnotations(self.mapView.annotations, animated: true) 

這是我用它來展示所有註釋。幾乎和你在做的一樣。地圖放大以適應地圖的可見或可用部分,在我的應用程序中,縮放比較好,並且添加了一些填充,以便任何引腳都不會觸及邊緣。

因此,一旦地圖完成,您可以快速使用setVisibleMapRect:edgePadding:animated:使用帶有負填充的新visibleRect。