Initialize a CLLocation object in swift with latitude and longitude

33,004

Solution 1

I am not near my Mac to test it but the following should be working. Just pass your lat and lon values to the CLLocaion initializer like this:

let myLocation = CLLocation(latitude: your_latitiude_value, longitude: your_longitude_value) 

For reference you can check the documentation

Solution 2

If all you want is the initializer that takes a lat and long, your code can look like this:

let latitude: CLLocationDegrees = 37.2
let longitude: CLLocationDegrees = 22.9

let location: CLLocation = CLLocation(latitude: latitude, 
  longitude: longitude)

There are other initializers that take more parameters, but you didn't ask about those.

Share:
33,004

Related videos on Youtube

Henrik Holm
Author by

Henrik Holm

Updated on July 16, 2022

Comments

  • Henrik Holm
    Henrik Holm almost 2 years

    In objective C (I have no experience with it) you can initialize a CLLocation object with latitude and longitude likes this:

    CLLocation *myLocation = [[CLLocation alloc]  initWithLatitude:your_latitiude_value longitude:your_longitude_value];
    

    But how do I do it in Swift?

    I tried this,

    let loc_coords = CLLocationCoordinate2D(latitude: your_latitiude_value, longitude: your_longitude_value)
    
    let loc = CLLocation().coordinate(loc_coords)
    

    But I get this error:

    Cannot invoke "coordinate" with an argument list of type '(CLLocationCoordiate2D)'

    I need it to be a CLLocation object as I want to use the distanceFromLocation method within the locationManager.

    Hope you can help, thanks!

  • Duncan C
    Duncan C about 9 years
    Yup, you got it, and you pressed return before I did (I went and verified it in a Playground, so I'm sure it's correct.)
  • Henrik Holm
    Henrik Holm about 9 years
    Bah of course, thats quiet logical. But thanks a lot!