I'm having trouble getting a Google Map to center itself and add a marker when it's a subview connected as an IBOutlet. I have tried to get it work it feels like 20 different ways, but am stuck so would appreciate any help or guidance.
The code setup is pretty straightforward as follows:
//Map view outlet
@IBOutlet weak var googleMapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Google Map View Setup
let camera = GMSCameraPosition.cameraWithLatitude(-33.86, longitude: 151.20, zoom: 6)
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
mapView.myLocationEnabled = true
self.googleMapView = mapView
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(-33.86, 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
I can get it to work if the view is the entire View Controller by changing self.googleMapView to self.view, but I can't figure out how to get it connected properly to the googleMapView outlet. Thanks!
I tried using the help given for this similar question but it's not clearly answered because the outlet and the variable are both mapView and I couldn't get it to work.
Well of course after I asked the question to everyone here I had an epiphany and figured it out! I didn't need to create a new GMSMapView because that was already done with autolayout. I just needed to access the camera variable of the that GMSMapView Outlet to set the position.
Code below:
// Google Map View Setup
let camera = GMSCameraPosition.cameraWithLatitude(-33.86, longitude: 151.20, zoom: 6)
self.googleMapView.myLocationEnabled = true
self.googleMapView.camera = camera
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(-33.86, 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = googleMapView
I think your mapView bounds are not setting properly to the view outlet in viewDidLoad() function. So you can set the mapView bounds from func viewDidAppear(animated: Bool).I had faced the same issue that google map is centering on the self.view properly and not centering on custom view bounds.We found the reason that on func viewDidLoad(),we cant get the rectangle bounds of the view properly.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
googleMapsView = GMSMapView()
googleMapsView?.frame = mapView.bounds
googleMapsView?.myLocationEnabled = true
if let googleMapView = googleMapsView {
mapView.addSubview(googleMapView)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With