如何使用google maps sdk为iOS拟合坐标数组的边界? 我需要缩放4个可见标记的地图。
答案 0 :(得分:66)
这是我解决这个问题的方法。通过多个坐标构建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 markers 属性,因此您应该将所有标记保存在自己的数组中。
更新swift 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)
}
答案 1 :(得分:6)
Swift 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))
}
}
你可以这样调用我的函数:
self.focusMapToShowMarkers(markers: [self.myLocationMarker, currentPokemonMarker])
答案 2 :(得分:3)
暂时,Google终于实施了GMSCoordinateBounds, 你可以使用GMSCameraUpdate来使用它。
有关详细信息,请查看官方reference。
答案 3 :(得分:0)
迅速5 版本的Lirik的答案:
func focusMapToShowAllMarkers() {
if arrMarkers.count > 0 {
let firstLocation = (arrMarkers.first!).position
var bounds = GMSCoordinateBounds(coordinate: firstLocation, coordinate: firstLocation)
for marker in arrMarkers {
bounds = bounds.includingCoordinate(marker.position)
}
let update = GMSCameraUpdate.fit(bounds, withPadding: CGFloat(15))
self.mapView.animate(with: update)
}
}
答案 4 :(得分:0)
我们可以使用如下代码将其简化:
extension Array where Element: GMSMarker {
func encompassingCoordinateBounds() -> GMSCoordinateBounds {
reduce(GMSCoordinateBounds(), { $0.includingCoordinate($1.position) })
}
}
呼叫站点希望:
let markers = [GMSMarker]()
let encompassingCoordinateBounds = markers.encompassingCoordinateBounds()