Google Maps GMSMapView on custom UIView
If you want to add a mapView
after the loading of the view
, then you need to create an object of GMSMapView
. So break the outlets of your mapView
since it will be created dynamically.
import UIKit
import GoogleMaps
class MapViewController: UIViewController {
//Take a Google Map Object. Don't make outlet from Storyboard, Break the outlet of GMSMapView if you made an outlet
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))
//so the mapView is of width 200, height 200 and its center is same as center of the self.view
mapView?.center = self.view.center
self.view.addSubview(mapView!)
}
}
Here is the output. mapView
is of width = 200 and height = 200 with center as same as self.view
I finally figured out how to display the map in a UIView created in Storyboard and center it in a specific location.
Note: After created the UIView outlet, I changed its class to GMSMapView as explained before.
import UIKit
import GoogleMaps
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.camera(withLatitude: 52.520736, longitude: 13.409423, zoom: 12)
self.mapView.camera = camera
let initialLocation = CLLocationCoordinate2DMake(52.520736, 13.409423)
let marker = GMSMarker(position: initialLocation)
marker.title = "Berlin"
marker.map = mapView
}
And this is the output: Map centred in Berlin