[英]Is there an IOS API that wraps the google 'distance between two locations' API?
[英]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.