简体   繁体   中英

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

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)

Swift 5+:
As far as I know, there are two ways to find the distance. If you are looking for driving distance, you can always use MKDirections. Here is the code for finding driving distance (You can also find walking, and transit distance by changing transport type).

let sourceP = CLLocationCoordinate2DMake( sourceLat, sourceLong)
let destP = CLLocationCoordinate2DMake( desLat, desLong)
let source = MKPlacemark(coordinate: sourceP)
let destination = MKPlacemark(coordinate: destP)
        
let request = MKDirections.Request()
request.source = MKMapItem(placemark: source)
request.destination = MKMapItem(placemark: destination)

// Specify the transportation type
request.transportType = MKDirectionsTransportType.automobile;

// If you want only the shortest route, set this to a false
request.requestsAlternateRoutes = true

let directions = MKDirections(request: request)

 // Now we have the routes, we can calculate the distance using
 directions.calculate { (response, error) in
    if let response = response, let route = response.routes.first {
                print(route.distance) //This will return distance in meters
    }
 }

If you are only looking for air distance/bird's eye distance/coordinate distance, you can use this code:

let sourceP = CLLocation(latitude: sourceLat, longitude: sourceLong)
let desP = CLLocation(latitude: desLat, longitude: desLong))

let distanceInMeter = sourceP.distance(from: desP)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM