Reputation: 8020
I have an issue using getting lat and long from a CLLocation object.
The weird thing is, up until yesterday I was able to retrieve the lat and long by doing:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var location: AnyObject? = locations.last
if let location: AnyObject = location {
//The println illustrates how I would retrieve the lat and long, i.e. by calling
//location.coordinate.latitude.
println(location.coordinate.latitude)
locationDelegate?.updateLabels(location)
self.locationsArray.append(location)
}
}
This has now stopped working and it throws me the following compiler error:
If i remove the .coordinate
call and call .latitude
directly on the location
object, it just returns nil
. I'm a bit lost as to whats going on here...
if I println(location)
i get the following output:
<+56.92239472,+1.47020887> +/- 5.00m (speed -1.00 mps / course -1.00) @ 10/11/14, 2:37:59 PM British Summer Time
Can anybody help me understand whats going on and how to retrieve the lat and long again?
Upvotes: 0
Views: 932
Reputation: 2335
The best way to implement this method is to define the coordinates. (i assume you trying to get the current location)
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if !isCurrentLocation {
return
}
isCurrentLocation = false
let location = locations.last
// here define the center variable to hold the coordinates for reuse!
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: DesiredLocation.latitude, longitudeDelta: DesiredLocation.longitude))
self.mapView.setRegion(region, animated: true)
}
And its all set!
Upvotes: 0
Reputation: 618
I had this problem. The proper solution is to cast the location objects to CLLocation before you dereference the coordinate property. The following code should work, although I haven't actually tested it. Additionally, there may be a more elegant way to do the cast; I'm still learning Swift myself.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var location: AnyObject? = locations.last
if let location: AnyObject = location {
//The println illustrates how I would retrieve the lat and long, i.e. by calling
//location.coordinate.latitude.
var loc = location as CLLocation
println(loc.coordinate.latitude)
locationDelegate?.updateLabels(loc)
self.locationsArray.append(loc)
}
}
Upvotes: 0
Reputation: 8020
Using the func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!)
instead of the above delegate method and then calling newLocation.coordinate.latitude
seems to work.
Upvotes: 1