Search code examples
iosswiftgoogle-mapsgeolocationgeocoding

How to calculate distance between two locations using google api in swift 4


I am currently working on an IOS project in which i have to calculate distance between two location. I have done without using google but i want to use google api to get accurate distance i am sharing my code here

    let myLocation = CLLocation(latitude: CLLocationDegrees(latittude[indexPath.row])!, longitude: CLLocationDegrees(longittude[indexPath.row])!)
        let lat = UserDefaults.standard.string(forKey: "lat") ?? ""
        let long = UserDefaults.standard.string(forKey: "long") ?? ""
        let myBuddysLocation = CLLocation(latitude: CLLocationDegrees(lat)!, longitude: CLLocationDegrees(long)!)

Solution

  • Use distance function of CoreLocation Framework,

     var startLocation = CLLocation(latitude: startLatitude, longitude: startLongitude)
     var endLocation = CLLocation(latitude: endLatitude, longitude: endLongitude)
     var distance: CLLocationDistance = startLocation.distance(from: endLocation)