Pierre Olivier Tran
Pierre Olivier Tran

Reputation: 1879

Convert string to CLLocationCoordinate

Is it possible to convert a string to a longitude/latitude value? I managed to convert the coordinate to a string, but I cannot find a way to revert the process

Upvotes: 5

Views: 15973

Answers (5)

g89n7man
g89n7man

Reputation: 59

might help

let Latitude = ("41" as NSString).doubleValue
let Longitude = ("29" as NSString).doubleValue

Upvotes: 1

Anji Mendpara
Anji Mendpara

Reputation: 90

var currentLocationLatitude = "45.5626" // your string latitude
var currentLocationLongitude = "45.5626" // your string longitude

var currentLocation:CLLocationCoordinate2D! //location object

currentLocation = CLLocationCoordinate2D(latitude:currentLocationLatitude.toDouble() ?? 0.0, longitude: currentLocationLongitude.toDouble() ?? 0.0) 



extension String
{
    /// EZSE: Converts String to Double
    public func toDouble() -> Double?
    {
       if let num = NumberFormatter().number(from: self) {
                return num.doubleValue
            } else {
                return nil
            }
     }
}

You can take string latitude and longitude from you API response and in CLLocationCoordinate2D variable, pass with converting to Double value. I have also added extension for converting string to double.

Upvotes: 1

kiran pm
kiran pm

Reputation: 151

Swift 3

let lat = Double(String1)
let lon = Double(String2)

 let coordinates = CLLocationCoordinate2D(latitude:lat!
                        , longitude:lon!)

CLLocationCoordinate2D is a double value it can convert string into double See in above example

Upvotes: 9

sanjana
sanjana

Reputation: 3034

Another way to convert:

let latitude = (latitudeString as NSString).doubleValue
let longitude = (longitudeString as NSString).doubleValue

Upvotes: 9

Pierre Olivier Tran
Pierre Olivier Tran

Reputation: 1879

My bad, it was a simple type. If anyone ever struggle on how to convert a string to coordinates, here's the correct syntax :

let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: Double(([longitudeString] as NSString).doubleValue), longitude: Double(([LatitudeString] as NSString).doubleValue))

Upvotes: 7

Related Questions