Swift - 谷歌地图因“意外发现的零”错误而崩溃

时间:2016-12-27 04:47:08

标签: ios swift google-maps swift3 xcode8

我正在尝试将GoogleMap设置为UIView并将其添加为子视图。但是,在运行应用程序时,我收到此错误:

  

致命错误:在解包可选值时意外发现nil

它在代码行崩溃:

mapView.camera = camera

这是我的完整ViewController代码:

class LocationViewController: UIViewController {
    @IBOutlet weak var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let camera = GMSCameraPosition.camera(withLatitude: 15.4989, longitude: 73.8278, zoom: 6)
        mapView.camera = camera
        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.isMyLocationEnabled = true
        mapView.settings.myLocationButton = true
        self.view.addSubview(self.mapView)
    }
}

我经历了一些其他类似的SO线程,所有这些线程都有相同的代码。在我的情况下,UI冻结并崩溃与此错误。我做错了什么?

修改

是的,我已将UIView的自定义类设置为GMSMapView

3 个答案:

答案 0 :(得分:0)

请您使用以下代码并尝试:

override func viewDidLoad() {
        super.viewDidLoad()

        let camera = GMSCameraPosition.camera(withLatitude: 15.4989, longitude: 73.8278, zoom: 6)
        mapView.camera = camera
        mapView.isMyLocationEnabled = true
        mapView.settings.myLocationButton = true
        self.view.addSubview(self.mapView)
    }

答案 1 :(得分:0)

你必须这样做

你必须给GMSMapview框架
在此行self.view.bounds中,您必须设置自定义view

let camera = GMSCameraPosition.camera(withLatitude: 15.4989,
                                      longitude:  73.8278,
                                      zoom: 6)
let mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)

答案 2 :(得分:0)

这是swift 3.0中的语法

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
{
    print(locations)
    mapview.delegate = self
 currentLocation =     CLLocationCoordinate2D(latitude:CLLocationDegrees(locations[0].coordinate.latitude), longitude:CLLocationDegrees(locations[0].coordinate.longitude))
    mapview.camera = GMSCameraPosition.camera(withTarget:locations[0].coordinate, zoom: 10.0)
mapview.isMyLocationEnabled = true
}