2013-02-28 74 views

回答

56

这是我对这个问题的解决方案。通过多个坐标构建GMSCoordinateBounds对象。

- (void)focusMapToShowAllMarkers 
{  
    CLLocationCoordinate2D myLocation = ((GMSMarker *)_markers.firstObject).position; 
    GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:myLocation coordinate:myLocation]; 

    for (GMSMarker *marker in _markers) 
     bounds = [bounds includingCoordinate:marker.position]; 

    [_mapView animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds withPadding:15.0f]]; 
} 

更新答案:由于GMSMapView中标记财产已被弃用,您应该保存所有标记在自己的阵列。

更新迅速的3回答:

func focusMapToShowAllMarkers() { 
     let firstLocation = (markers.first as GMSMarker).position 
     var bounds = GMSCoordinateBoundsWithCoordinate(firstLocation, coordinate: firstLocation) 

     for marker in markers { 
      bounds = bounds.includingCoordinate(marker.position) 
     } 
     let update = GMSCameraUpdate.fitBounds(bounds, withPadding: CGFloat(15)) 
     self.mapView.animate(cameraUpdate: update) 
    } 
+2

工作正常。虽然标记属性现在已被弃用。我使用了数组中的标记位置。 – 2013-12-15 08:30:03

+0

谢谢,我用这个很棒的解决方案:)但是@ManishAhuja说,我用我自己存储的GMSMarker数组来构建边界。 – 2014-08-19 19:07:06

+0

谢谢@ManishAhuja和AubadaTaijo。 Iv'e更新了答案。 – Lirik 2014-08-20 20:29:50

3

暂时,谷歌终于实现了GMSCoordinateBounds, ,您可以使用它与GMSCameraUpdate。

详情请查看官方reference

5

雨燕3.0版本Lirik的回答:

func focusMapToShowAllMarkers() { 
    let myLocation: CLLocationCoordinate2D = self.markers.first!.position 
    var bounds: GMSCoordinateBounds = GMSCoordinateBounds(coordinate: myLocation, coordinate: myLocation) 

    for marker in self.markers { 
     bounds = bounds.includingCoordinate(marker.position) 
     self.mapView.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0)) 
    } 
} 

下面是我自己的方式:

func focusMapToShowMarkers(markers: [GMSMarker]) { 

    guard let currentUserLocation = self.locationManager.location?.coordinate else { 
     return 
    } 

    var bounds: GMSCoordinateBounds = GMSCoordinateBounds(coordinate: currentUserLocation, 
                  coordinate: currentUserLocation) 

    _ = markers.map { 
     bounds = bounds.includingCoordinate($0.position) 
     self.mapView.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0)) 
    } 
} 

你可以叫我功能如上所示:

​​