簡體   English   中英

如何使用谷歌計算兩個位置之間的距離 api in swift 4

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

我目前正在從事一個 IOS 項目,我必須在其中計算兩個位置之間的距離。 我沒有使用谷歌就完成了,但我想使用谷歌 api 來獲得准確的距離我在這里分享我的代碼

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

使用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+:
據我所知,有兩種方法可以找到距離。 如果您正在尋找行駛距離,您可以隨時使用 MKDirections。 這是查找行車距離的代碼(您還可以通過更改交通類型來查找步行和公交距離)。

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
    }
 }

如果你只是在尋找空中距離/鳥瞰距離/坐標距離,你可以使用這個代碼:

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

let distanceInMeter = sourceP.distance(from: desP)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM