Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit entire Google Map in zoom level in Swift project

I have a google map with a bunch of coordinates

path.addCoordinate(CLLocationCoordinate2DMake(-37.813047, 144.959911))
path.addCoordinate(CLLocationCoordinate2DMake(-37.814895, 144.960759))
path.addCoordinate(CLLocationCoordinate2DMake(-37.814361, 144.963140))
path.addCoordinate(CLLocationCoordinate2DMake(-37.812386, 144.962239))

I would like the map to be automatically zoomed to the best level based on the points however I can't find anything relating to this.

I have this working:

var vancouver = CLLocationCoordinate2DMake(-37.813047, 144.959911)
var calgary = CLLocationCoordinate2DMake(-37.814361, 144.963140)
var bounds = GMSCoordinateBounds(coordinate: vancouver, coordinate: calgary)
var camera = viewMap.cameraForBounds(bounds, insets:UIEdgeInsetsZero)
viewMap.camera = camera

however it only accepts 2 coordinates where I may have up to 100

Thanks

like image 516
puks1978 Avatar asked Mar 16 '23 16:03

puks1978


1 Answers

You can use GMSCoordinateBounds(path:) to fit all coordinates. But it will display a world size scale if you update the camera right after your another update. So you can use dispatch_after to solve the problem.

 override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor();
        let camera = GMSCameraPosition.cameraWithLatitude(-37.813047, longitude: -72.8561644, zoom:5)
        mapView = GMSMapView.mapWithFrame(CGRectZero, camera:camera)

        let marker = GMSMarker()
        marker.position = camera.target
        marker.snippet = "Hello World"
        marker.appearAnimation = kGMSMarkerAnimationPop
        marker.map = mapView

        self.view = mapView

        delay(seconds: 2) { () -> () in
            let path = GMSMutablePath()
            path.addCoordinate(CLLocationCoordinate2DMake(37.36, -122.0))
            path.addCoordinate(CLLocationCoordinate2DMake(37.45, -122.0))
            path.addCoordinate(CLLocationCoordinate2DMake(37.45, -122.2))
            path.addCoordinate(CLLocationCoordinate2DMake(37.36, -122.2))
            path.addCoordinate(CLLocationCoordinate2DMake(37.36, -122.0))

            let rectangle = GMSPolyline(path: path)
            rectangle.map = self.mapView

            let bounds = GMSCoordinateBounds(path: path)

            self.mapView!.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds, withPadding: 15.0))
        }
    }

The delay method uses the dispatch_after:

func delay(#seconds: Double, completion:()->()) {
    let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds ))

    dispatch_after(popTime, dispatch_get_main_queue()) {
        completion()
    }
}

enter image description here

like image 188
ztan Avatar answered Mar 23 '23 13:03

ztan