2016-12-27 57 views
0

我想設置GoogleMapUIView並將其添加爲子視圖。但是,在運行應用程序時,我得到這個錯誤:Swift - 谷歌地圖與'意外發現零'錯誤崩潰

fatal error: unexpectedly found nil while unwrapping an Optional value

它崩潰的代碼行:

mapView.camera = camera 

這裏是我的完整視圖控制器代碼:

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

+0

其中線你有錯誤的語法? –

+0

@Jecky at'mapView.camera = camera' – Dinuka

+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) 
    } 
+0

你做了什麼改變? – Dinuka

+0

你的mapview框架 –

+0

這個代碼在swift-3 bro中有點不同:/ – Dinuka

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) 
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 
}