Search code examples
swiftgmsmapview

How to set/update zoom level to GMSMapView in Swift?


Following code is how I got new marker position and update mapview.

if self.state.dropOff != nil {   
                let loc = response
                let position = CLLocationCoordinate2D(latitude: loc.latitude!, longitude: loc.longitude!)
                self.getPolylineRoute(from: self.state.pickUp!.coordinate, to: self.state.dropOff!.coordinate)
                CATransaction.begin()
                CATransaction.setAnimationDuration(1.0)

                if self.acceptedCabMarker == nil {
                    self.acceptedCabMarker = GMSMarker(position: position)
                }

                self.acceptedCabMarker!.position = position
                self.acceptedCabMarker!.isFlat = true
                self.acceptedCabMarker!.icon = UIImage(named: markerIcon)
                self.acceptedCabMarker!.setIconSize(scaledToSize: .init(width: 40, height: 40))
                self.acceptedCabMarker!.appearAnimation = .pop
                self.acceptedCabMarker!.rotation = CLLocationDegrees(loc.bearing ?? 0)


                CATransaction.commit()
                DispatchQueue.main.async {
                    self.acceptedCabMarker!.map = self.mapView
                }
            }

Problem is everytime this code is executed, mapview zoom level became to its original state. Which mean user can't zoom the map for long. I tried to save the zoom using method.

extension SomeHomeViewController: GMSMapViewDelegate {

func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
    print("Camera Zoom: \(position.zoom)")
    currentPosition = position
}
}

But I can't reuse currentPosition because

self.mapView?.camera.zoom = currentPosition?.zoom

is not allowed.


Solution

  • You need to use

    - (void)animateToZoom:(float)zoom;
    

    method which is defined in GMSMapView (Animation) Category. For more info you can refer this link.