我使用Google Maps SDK在我的UIViewController中生成地图,但它在整个屏幕上生成地图。我只需要它就可以在屏幕的一半上创建一个地图。我该如何做到这一点?
class MapViewController: UIViewController,CLLocationManagerDelegate{
var locationManager = CLLocationManager()
var mapView = GMSMapView()
override func viewDidLoad() {
super.viewDidLoad()
// User Location
locationManager.delegate = self
//locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
view.backgroundColor = UIColor.gray
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation = locations.last
let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)
let camera = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude,
longitude: userLocation!.coordinate.longitude, zoom: 9.1)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.isMyLocationEnabled = true
self.view = mapView
locationManager.stopUpdatingLocation()
}
}
答案 0 :(得分:2)
请勿在{{1}}方法之外设置self.view
。
这里适当的解决方案是在loadView
中创建一次地图视图。将其添加为viewDidLoad
的子视图,而不是将其分配给self.view
。在self.view
中设置一次帧。根据需要将帧设置为屏幕的一半。
然后,如果需要,请在viewWillAppear
委托方法中更新地图视图的位置。
答案 1 :(得分:1)
在ViewController上创建一个与您想要的大小完全相同的视图,然后代替:
self.(insert your new view name here) = mapView
你可以做@yield('content')
答案 2 :(得分:0)
这是主要问题
self.view = mapView
您将mapView设置为self.view,这意味着屏幕上显示的完整视图尺寸
相反,在didLoad
中self.view.addSubview(mapView)
并在willAppear或didAppear
中设置框架mapView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width , height: self.view.frame.size.height/2)
答案 3 :(得分:0)
以下是解决此问题的步骤。
为您的地图视图创建@IBoutlet,请确保将其类型更改为GMSMapView!而不是常规的UIView类型!
@IBOutlet weak var mapView: GMSMapView!
让您的mapView并从身份检查器中,也更改类型并将其设置为GMSMapView! change the class type of the mapview
中,创建地图。如下
let camera = GMSCameraPosition.camera(withLatitude:-44.86,longitude:151.20, zoom:6.0)
let mapview = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.mapView = mapview