Search code examples
swiftswift2uilabelcore-locationibaction

IBAction to display latitude and longitude (swift)


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

Solution

  • 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.