[英]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.我目前正在从事一个 IOS 项目,我必须在其中计算两个位置之间的距离。 I have done without using google but i want to use google api to get accurate distance i am sharing my code here我没有使用谷歌就完成了,但我想使用谷歌 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)!)
Use distance function of CoreLocation Framework, 使用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+: 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.如果您正在寻找行驶距离,您可以随时使用 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.