I am trying to add a Google GMSMapView programmatically but got stuck and would appreciate any help. I want to set the constraints of the Map to the edges of the view.
However, when I do this I get an error of, "Unable to activate constraint with anchors and because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies?"
var mapView:GMSMapView?
override func viewDidLoad() {
super.viewDidLoad()
mapView = GMSMapView.map(withFrame: CGRect(x: 100, y: 100, width: 200, height: 200), camera: GMSCameraPosition.camera(withLatitude: 51.050657, longitude: 10.649514, zoom: 5.5))
mapView?.center = self.view.center
mapView?.topAnchor.constraint(equalTo: view.topAnchor).isActive=true
mapView?.leftAnchor.constraint(equalTo: view.leftAnchor).isActive=true
mapView?.rightAnchor.constraint(equalTo: view.rightAnchor).isActive=true
mapView?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 60).isActive=true
self.view.addSubview(mapView!)
}
I can get Google Maps to load properly if leave out the anchors, so I believe I have it set up properly otherwise. I just don't understand the concept of how to set the anchors properly.
This solution is similar but is focused more on adding the View with auto layout.
The issue occurs when you apply constraints to a view before adding it the to parent view. Also set translatesAutoresizingMaskIntoConstraints to false to make the constraints work.
self.view.addSubview(mapView!)
mapView?.translatesAutoresizingMaskIntoConstraints = false
mapView?.topAnchor.constraint(equalTo: view.topAnchor).isActive=true
mapView?.leftAnchor.constraint(equalTo: view.leftAnchor).isActive=true
mapView?.rightAnchor.constraint(equalTo: view.rightAnchor).isActive=true
mapView?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 60).isActive=true