热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

计算iOSSwift的总行进距离

如何解决《计算iOSSwift的总行进距离》经验,为你挑选了2个好方法。

如何计算在Swift中使用CoreLocation的总行程距离

到目前为止,我还没有找到任何有关如何在Swift for iOS 8中执行此操作的资源,

您如何计算自开始追踪您的位置以来移动的总距离?

从我到目前为止所读到的,我需要保存点的位置,然后计算当前点和最后一点之间的距离,然后将该距离添加到totalDistance变量

Objective-C对我来说是非常陌生的,所以我无法解决swift语法问题

这是我到目前为止所做的,不确定我是否做得对.虽然该distanceFromLocation方法返回所有0.0所以显然有些错误

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
     var newLocation: CLLocation = locations[0] as CLLocation

    oldLocationArray.append(newLocation)
           var totalDistance = CLLocationDistance()
    var oldLocation = oldLocationArray.last

    var distanceTraveled = newLocation.distanceFromLocation(oldLocation)

    totalDistance += distanceTraveled

 println(distanceTraveled)



}

Leo Dabus.. 18

更新:Xcode 8.3.2•Swift 3.1

问题在于因为你总是一遍又一遍地获得相同的位置.试试这样:

import UIKit
import MapKit

class ViewController: UIViewController,  CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    let locatiOnManager= CLLocationManager()
    var startLocation: CLLocation!
    var lastLocation: CLLocation!
    var startDate: Date!
    var traveledDistance: Double = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
            locationManager.startMonitoringSignificantLocationChanges()
            locationManager.distanceFilter = 10
            mapView.showsUserLocation = true
            mapView.userTrackingMode = .follow
        }
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if startDate == nil {
            startDate = Date()
        } else {
            print("elapsedTime:", String(format: "%.0fs", Date().timeIntervalSince(startDate)))
        }
        if startLocation == nil {
            startLocation = locations.first
        } else if let location = locations.last {
            traveledDistance += lastLocation.distance(from: location)
            print("Traveled Distance:",  traveledDistance)
            print("Straight Distance:", startLocation.distance(from: locations.last!))
        }
        lastLocation = locations.last
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        if (error as? CLError)?.code == .denied {
            manager.stopUpdatingLocation()
            manager.stopMonitoringSignificantLocationChanges()
        }
    }
}

示例项目



1> Leo Dabus..:

更新:Xcode 8.3.2•Swift 3.1

问题在于因为你总是一遍又一遍地获得相同的位置.试试这样:

import UIKit
import MapKit

class ViewController: UIViewController,  CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    let locatiOnManager= CLLocationManager()
    var startLocation: CLLocation!
    var lastLocation: CLLocation!
    var startDate: Date!
    var traveledDistance: Double = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
            locationManager.startMonitoringSignificantLocationChanges()
            locationManager.distanceFilter = 10
            mapView.showsUserLocation = true
            mapView.userTrackingMode = .follow
        }
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if startDate == nil {
            startDate = Date()
        } else {
            print("elapsedTime:", String(format: "%.0fs", Date().timeIntervalSince(startDate)))
        }
        if startLocation == nil {
            startLocation = locations.first
        } else if let location = locations.last {
            traveledDistance += lastLocation.distance(from: location)
            print("Traveled Distance:",  traveledDistance)
            print("Straight Distance:", startLocation.distance(from: locations.last!))
        }
        lastLocation = locations.last
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        if (error as? CLError)?.code == .denied {
            manager.stopUpdatingLocation()
            manager.stopMonitoringSignificantLocationChanges()
        }
    }
}

示例项目


第一个位置通常不精确.在开始更新之前,您可以丢弃它们

2> Icaro..:

如果要计算需要使用的两点之间的路径距离MKDirectionsRequest,这将通过分步指令返回从A点到B点的一条或多条路线:

class func caculateDistance(){
    var directiOnRequest= MKDirectionsRequest()
    var sourceCoord = CLLocationCoordinate2D(latitude: -36.7346287, longitude: 174.6991812)
    var destinatiOnCoord= CLLocationCoordinate2D(latitude: -36.850587, longitude: 174.7391745)
    var mkPlacemarkOrigen = MKPlacemark(coordinate: sourceCoord, addressDictionary: nil)
    var mkPlacemarkDestination = MKPlacemark(coordinate: destinationCoord, addressDictionary: nil)
    var source:MKMapItem = MKMapItem(placemark: mkPlacemarkOrigen)
    var destination:MKMapItem = MKMapItem(placemark: mkPlacemarkDestination)
    directionRequest.setSource(source)
    directionRequest.setDestination(destination)
    var directiOns= MKDirections(request: directionRequest)
    directions.calculateDirectionsWithCompletionHandler {
        (response, error) -> Void in
        if error != nil { println("Error calculating direction - \(error.localizedDescription)") }
        else {
            for route in response.routes{
                println("Distance = \(route.distance)")
                for step in route.steps!{
                    println(step.instructions)
                }  
            }
        }
    }
}

此示例代码将返回此信息:

Distance
Distance = 16800.0

Step by Step instructions
Start on the route
At the end of the road, turn left onto Bush Road
Turn right onto Albany Expressway
At the roundabout, take the first exit onto Greville Road toward 1, Auckland
At the roundabout, take the third exit to merge onto 1 toward Auckland
Keep left
Take exit 423 onto Shelly Beach Road
Continue onto Shelly Beach Road
At the end of the road, turn right onto Jervois Road
Turn left onto Islington Street
Keep right on Islington Street
Arrive at the destination

可以轻松修改该功能以接收两个位置并返回距离和任何其他所需信息.

我希望能帮到你!


推荐阅读
author-avatar
lucky燕子加加加
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有