谷歌地图GMSMarker改变了相机对焦iOS

时间:2018-05-29 06:22:00

标签: ios swift google-maps google-maps-markers

我遇到的问题是GMSMarker会将相机重点放在任何类型的弹出警报上,或者每当我点击标记和应用程序导航到谷歌地图应用程序时。以下是我的实施。我在layoutsubviews方法中将google maps容器添加到我的viewcontroller标头中。不知道发生了什么。请帮助。

override func viewDidLayoutSubviews()
    {
        super.viewDidLayoutSubviews()

        if mapView == nil
        {
            let camera = GMSCameraPosition.camera(withLatitude: 45.582045, longitude:74.32937, zoom: 14.0)
            mapView = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: self.mapContainerView.bounds.size.width, height: self.mapContainerView.bounds.size.height), camera: camera)
            mapView.delegate = self

            do {
                // Set the map style by passing the URL of the local file.
                if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
                    mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
                } else {
                    NSLog("Unable to find style.json")
                }
            } catch {
                NSLog("One or more of the map styles failed to load. \(error)")
            }

            self.mapContainerView.addSubview(mapView)
            mapView.settings.setAllGesturesEnabled(false)
            let marker = AppointmentMapDataManager(mapView: mapView).setAppointmentMarker()
//            let location = GMSCameraPosition.camera(withLatitude: marker.position.latitude,
//                                                  longitude: marker.position.longitude,
//                                                  zoom: 14)
//            mapView.camera = location
            var bounds = GMSCoordinateBounds()
            bounds = bounds.includingCoordinate((marker as AnyObject).position)
            let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsets(top: self.mapContainerView.frame.height/2 - 33, left: self.mapContainerView.frame.width/2 - 81, bottom: 0, right: 0))
            mapView.moveCamera(update)
        }
    }

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

不是在viewDidLayoutSubView中移动你的相机,这是一种错误的方法,而是使用GMSMapViewDelegate的didTap方法,或者如果你想在延迟后自动使用执行

//method for center camera based in your own code
func centerInMarker(marker: GMSMarker) {
    var bounds = GMSCoordinateBounds()
    bounds = bounds.includingCoordinate((marker as AnyObject).position)
    let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsets(top: (self.mapView?.frame.height)!/2 - 33, left: (self.mapView?.frame.width)!/2 - 81, bottom: 0, right: 0))
    mapView?.moveCamera(update)
}

您可以在委托方法

中使用它
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    self.centerInMarker(marker: marker)
    return true
}

或者只是在您添加标记时,有延迟

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
        self.centerInMarker(marker: marker)
}

答案 1 :(得分:0)

您应该添加viewDidLoad方法,并在frame更新viewDidLayoutSubviews