如何通过GMSCoordinateBounds创建并设置GMSCameraPosition?
解决Google Maps在SwiftUI中显示所有坐标的相机调整问题
你遇到的问题核心是**GMSCoordinateBounds是不可变对象**:调用includingCoordinate(_:)会返回一个新的bounds实例,但你原代码里没有将这个新实例重新赋值给变量,导致最终的bounds还是初始空值,相机自然无法正确调整范围。
正确创建GMSCoordinateBounds的方式
方法1:循环累加更新bounds
先判断坐标数组非空避免崩溃,再逐步扩展范围:
guard let firstCoord = coordinates.first else { return } var bounds = GMSCoordinateBounds(coordinate: firstCoord, coordinate: firstCoord) for coord in coordinates { bounds = bounds.includingCoordinate(coord) }
方法2:批量初始化更简洁
直接通过坐标数组初始化,省去循环步骤:
guard !coordinates.isEmpty else { return } let bounds = GMSCoordinateBounds(coordinates: coordinates, count: coordinates.count)
生成相机更新并应用
拿到有效bounds后,建议添加内边距避免标记被界面边缘遮挡,再更新相机:
// 设置100pt内边距,可根据实际布局调整 let cameraUpdate = GMSCameraUpdate.fit(bounds, withPadding: 100) // 直接跳转或带动画移动相机 mapView.moveCamera(cameraUpdate) // 带动画的写法:mapView.animate(withDuration: 0.5) { mapView.moveCamera(cameraUpdate) }
在SwiftUI的UIViewRepresentable中集成
通过绑定坐标数组,在updateUIView中自动触发相机调整,适配SwiftUI的状态更新逻辑:
struct GoogleMapView: UIViewRepresentable { @Binding var coordinates: [CLLocationCoordinate2D] func makeUIView(context: Context) -> GMSMapView { let mapView = GMSMapView(frame: .zero) // 可添加地图初始化配置(如样式、手势等) return mapView } func updateUIView(_ uiView: GMSMapView, context: Context) { guard !coordinates.isEmpty else { return } let bounds = GMSCoordinateBounds(coordinates: coordinates, count: coordinates.count) let cameraUpdate = GMSCameraUpdate.fit(bounds, withPadding: 100) uiView.moveCamera(cameraUpdate) } }
直接通过bounds创建GMSCameraPosition
你也可以用bounds直接生成目标相机位置,再赋值给地图:
guard !coordinates.isEmpty else { return } let bounds = GMSCoordinateBounds(coordinates: coordinates, count: coordinates.count) let targetCamera = GMSCameraPosition.fit(bounds, withPadding: 100) mapView.camera = targetCamera
内容的提问来源于stack exchange,提问作者Berry Blue
相关产品推荐
相关产品推荐

