Change Camera Zoom based on Radius Google Maps iOS SDK

Granit picture Granit · Sep 30, 2014 · Viewed 8.5k times · Source

I am working on an app that displays certain markers based on a radius around your current location. The radius is between 100 - 5000 meters. I change the radius with an UISlider and redraw the GMSCircle.

My problem is that I want to update the camera zoom according to the slider value but I don't have an idea by which scale to divide.

This is how I create the camera in the viewDidLoad method where the initial zoom value is 15:

GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude  zoom:15];

Here's a screenshot of what I am working on.

enter image description here

Does anyone know what scale should I use to move the zoom accordingly?

Thanks a lot!

Granit

Answer

Vlad Lego picture Vlad Lego · Feb 7, 2016

Here's a simpler solution for getting the bounds of a GMSCircle. It doesn't rely on MapKit and avoids the two calls that change the camera position (moveCamera and animateToLocation)

import GoogleMaps

extension GMSCircle {
    func bounds () -> GMSCoordinateBounds {
        func locationMinMax(_ positive : Bool) -> CLLocationCoordinate2D {
            let sign: Double = positive ? 1 : -1
            let dx = sign * self.radius  / 6378000 * (180 / .pi)
            let lat = position.latitude + dx
            let lon = position.longitude + dx / cos(position.latitude * .pi / 180)
            return CLLocationCoordinate2D(latitude: lat, longitude: lon)
        }

        return GMSCoordinateBounds(coordinate: locationMinMax(true),
                               coordinate: locationMinMax(false))
    }
}

After adding this file to your project, all you have to do is:

let update = GMSCameraUpdate.fit(myCircle.bounds())
myMap.animate(with: update)

where myCircle and myMap are replaced by the actual circle and map.