Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving Google Maps Camera to a Location

I'm working with a Google Maps View and I want to add a button to the map that when tapped, will move the camera to a specific location. I currently have a button outlet and an action connected to the button.

@IBAction func locationTapped(_ sender: Any) {
    print("tapped")
    let location = GMSCameraPosition.camera(withLatitude: place.latitude, longitude: place.longitude, zoom: 17.0)

    mapView.camera = location
}

place exists but for some reason, the camera will not budge. I've tried different versions of code and looked at the Google Maps documentation but none of the options are producing results. Can anyone tell me what I'm doing wrong?

like image 901
ch1maera Avatar asked May 13 '17 01:05

ch1maera


2 Answers

The GMSMapView class has the following function:

animate(to: GMSCameraPosition)

So in your code sample, instead of doing this:

mapView.camera = location

Try doing this:

mapView.animate(to: location)

Hope this helps!

like image 122
Pheepster Avatar answered Sep 28 '22 07:09

Pheepster


in Swift3 and Swift4 for moving marker to current position use this:

func myLocationBtnAction(_ sender: UIButton) {
            mapView.moveCamera(GMSCameraUpdate.setTarget(CLLocationCoordinate2D(latitude: (mapView.myLocation?.coordinate.latitude)!, longitude: (mapView.myLocation?.coordinate.longitude)!), zoom: 16))

and for a specific location use this:

let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 16)
            mapView?.camera = camera
            mapView?.animate(to: camera)

and don't forget to extend GMSAutocompleteViewControllerDelegate for current location

like image 31
Mohsen mokhtari Avatar answered Sep 28 '22 06:09

Mohsen mokhtari