Jay
Jay

Reputation: 5074

Swift - Google Map crashes with 'unexpectedly found nil' error

I am trying to set a GoogleMap to a UIView and add it as a Subview. However, when running the app I get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

It crashes at code line:

mapView.camera = camera

Here's my full ViewController code:

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

I went through a few other similar SO threads and all of them have the same code. In my case the UI freezes and crashes with this error. What am I doing wrong?

EDIT

Yes, I have set the UIView's custom class as GMSMapView

Upvotes: 0

Views: 1458

Answers (3)

priya.vr
priya.vr

Reputation: 239

This is the syntax in 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
}

Upvotes: 0

Jitendra Modi
Jitendra Modi

Reputation: 2394

you have to do it like this

you have to give frame to GMSMapview
Here in this line self.view.bounds , you have to set your custom view

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

Upvotes: 0

Dheeraj D
Dheeraj D

Reputation: 4451

Could you please use below code and try:

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

Upvotes: 0

Related Questions