0

I am making a single view application in Xcode, with Google Map SDK. I have followed instructions online and my application can successfully load the google map view. I have also enabled myLocation, so that myLocation button shows on the map view.

I understand that clicking the myLocation button will change the camera location automatically, but I'm wondering what I should do to use the data of myLocation (say to add a marker or add a path node)?

I've tried directly accessing mapView.myLocation, for example

let lat = mapView.myLocation?.coordinate.latitude
let long = mapView.myLocation?.coordinate.longitude
path.addCoordinate(CLLocationCoordinate2D(latitude: lat!, longitude: long!))

However, this will crash the applicaton and throw:

fatal error: unexpectedly found nil while unwrapping an Optional value

What does this error message mean and how should I resolve this?

double-beep
  • 5,031
  • 17
  • 33
  • 41
CatSensei
  • 1
  • 2
  • Do you have permission to get the user location? Try this code in the section "My Location" https://developers.google.com/maps/documentation/ios-sdk/map#accessibility – Ulysses Mar 04 '16 at 22:07
  • @UlyssesR Thank you for your comment! I tried this code, and the result is "user location is unknown". But I'm confused about this since the application is showing my current location with the blue dot, and the myLocation button works correctly. – CatSensei Mar 04 '16 at 22:30
  • https://stackoverflow.com/questions/34956217/current-location-in-google-maps-with-swift/48062722#48062722 – Masoud Roosta Feb 29 '20 at 04:39

2 Answers2

0

The error says that myLocation property of mapView is nil. You should check if there is a value before accessing it.

if let myLocation = mapView.myLocation {
    let lat = myLocation.coordinate.latitude
    let long = myLocation.coordinate.longitude
    path.addCoordinate(CLLocationCoordinate2D(latitude: lat, longitude: long))
}

Also verify why myLocation is nil. It might be that the user didn't allow location services.

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
  • Thank you for answering! I believe I have turn on location services, as the application is showing my current location with blue spot, and the myLocation button works correctly. Why would the myLocation variable be nil in this case? – CatSensei Mar 04 '16 at 22:34
  • @CatSensei Edit your question and show your code for your myLocation button. This may help clear up some questions, and always try to include other code when it's referred to. – MwcsMac Mar 05 '16 at 05:18
-1

This will not give any errors:

let lat = mapView.myLocation?.coordinate.latitude ??  give any value of latitude 
let long = mapView.myLocation?.coordinate.longitude ?? give any value of longitude
double-beep
  • 5,031
  • 17
  • 33
  • 41
omkar marathe
  • 61
  • 1
  • 7