0

I have code that gets the users location. I want the user to be able to press a button and see their coordinates onscreen. how do I do this as I can't call myLat or MyLong for the button function directly as it is a location manager function. why isn't this code working?

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    // get most recient coordinate
    let myCoor = locations[locations.count - 1]

    //get lat & long
    var myLat = myCoor.coordinate.latitude
    let myLong = myCoor.coordinate.longitude
    let myCoor2D = CLLocationCoordinate2D(latitude: myLat, longitude: myLong)

    //set span
    let myLatDelta = 0.05
    let myLongDelta = 0.05
    let mySpan = MKCoordinateSpan(latitudeDelta: myLatDelta, longitudeDelta: myLongDelta)

    let myRegion = MKCoordinateRegion(center: myCoor2D, span: mySpan)
    self.LocationManager.stopUpdatingLocation()
 }




@IBAction func coo(sender: AnyObject) {
     self.coolat.text! = String(myLat)
     self.coolong.text! = String(myLong)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
kitchen800
  • 197
  • 1
  • 12
  • 36

2 Answers2

0

Since your locationManager variables myLat and myLong are local only to that function, just declare two global variables that are (a) set by locationManager and (b) are then pulled by the IBAction function.

  • I have set them globally however when they are called for the IBAction they only appear as 0.0. I have declared them globally as var myLat = CLLocationDegrees() and var myLong = CLLocationDegrees(). Why do they appear just as 0.0 and not the actual coordinates? – kitchen800 Nov 29 '16 at 14:48
  • In order of how to debug this, (1) set two breakpoints, one right after you populate the global variables and one inside your IBAction, (2) make sure you are populating things correctly - I'm guessing you are. If so, then you probably need to do a better type conversion - 0.05 can actually be displayed as 0.0! Look at this thread for how to format: [link]http://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift#24102844 –  Nov 29 '16 at 15:55
0

Declare myLat and myLong outside the function. You can update these inside locationManager() and these values can be used in labels.

Alex Thomas
  • 38
  • 10