在里程数计算中我的距离计算似乎是错误的

时间:2017-02-12 09:51:18

标签: swift3 xcode8.2

我有用户的当前位置和特定位置。我试图以英里为距离。我在英里的距离似乎是错误的,我在我的应用程序上获得了1.2英里,然后我在谷歌地图中检查了里程。我在谷歌地图上获得了2.1英里。这是我的代码,我不知道为什么我的代码不准确。请帮忙。

var locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    map.delegate = self
    map.userTrackingMode = MKUserTrackingMode.follow

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

    // set location
    let latitude: CLLocationDegrees = 32.5850
    let longitude: CLLocationDegrees = -85.4904
    let latDelta: CLLocationDegrees = 0.05
    let lonDelta: CLLocationDegrees = 0.05
    let span: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
    let coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    let region = MKCoordinateRegion(center: coordinates, span: span)

    map.setRegion(region, animated: true)

    // add annotation 
    let annotation = MKPointAnnotation()
    annotation.title = "1100 S College St"
    annotation.coordinate = coordinates

    map.addAnnotation(annotation)

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation: CLLocation = locations[0]
    let latitude = userLocation.coordinate.latitude
    let longitude = userLocation.coordinate.longitude

    let location1 = CLLocation(latitude: 32.5850, longitude: -85.4904) // set location

    let location2 = CLLocation(latitude: latitude, longitude: longitude) // user's current location

    let distanceInMeters : CLLocationDistance = location1.distance(from: location2) // distance in meters

    let distanceInMiles = distanceInMeters/1609.344  // distance in miles

    let roundUp = String(format:"%.1f", distanceInMiles) // round up

    distanceLabel.text = "\(roundUp) mi"

}

2 个答案:

答案 0 :(得分:1)

这部分是正确的:

let distanceInMiles = distanceInMeters/1609.344  // distance in miles

以米为单位检查距离并与Google地图进行比较。 如果您在iOS 10,则可以使用新的Measurement及相关类:

let meters = 1000.0

let distanceMeters = Measurement(value: meters, unit: UnitLength.meters)

let distanceMiles = distanceMeters.converted(to: UnitLength.miles)
let miles = distanceMeters.converted(to: UnitLength.miles).value

此代码产生以下结果: enter image description here

答案 1 :(得分:1)

Swift 4,XCode9

extension CLLocation {

    func myDistance(coordinate: CLLocation)->String{

        let distanceInMeters = self.distance(from: coordinate)

        if distanceInMeters < 1000 {
            return distanceInMeters.description + " M"
        }else{
            let distanceInKilometer = distanceInMeters /  1000
            return String(format:"%.1f", distanceInKilometer) + " KM"
        }

    }

}