即使在不同的位置,位置也永远不会更新,这可能是问题所在

时间:2018-10-11 04:17:55

标签: swift3

我构建了一个可跟踪我的位置的地图应用。我已经设置了MapKit和info,plist以及CLLocation。

问题:启动地图后,即使我在其他位置,也不会更新位置。

下面是代码:

import UIKit
import MapKit
import CoreLocation


class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var theMap: MKMapView!

    @IBOutlet weak var theLabel: UILabel!

    var manager:CLLocationManager!
    var myLocations: [CLLocation] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //Setup our Location Manager
        manager = CLLocationManager()
        //
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()

        //Setup 
        theMap.delegate = self
        theMap.mapType = MKMapType.standard
            //MKMapType.satellite
        theMap.showsUserLocation = true

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

        theLabel.text = "\(locations[0])"
        myLocations.append(locations[0] as CLLocation)

        let spanX = 0.01
        let spanY = 0.01
        let newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
        theMap.setRegion(newRegion, animated: true)

        if (myLocations.count > 1){
            let sourceIndex = myLocations.count - 1
            let destinationIndex = myLocations.count - 2

            let c1 = myLocations[sourceIndex].coordinate
            let c2 = myLocations[destinationIndex].coordinate
            var a = [c1, c2]
            // &a : direct get from this address of a
            let polyline = MKPolyline(coordinates: &a, count: a.count)
            theMap.add(polyline)
        }
    }

    func mapView(_ mapView: MKMapView!, rendererFor overlay: MKOverlay!) -> MKOverlayRenderer! {

        if overlay is MKPolyline {
            let polylineRenderer = MKPolylineRenderer(overlay: overlay)
            polylineRenderer.strokeColor = UIColor.blue
            polylineRenderer.lineWidth = 4
            return polylineRenderer
        }
        return nil
    }



}

1 个答案:

答案 0 :(得分:0)

添加此

  • 添加距离过滤器告诉locationManager在给定距离后至少应进行更新

  • 添加activityType可以为“核心位置”构想提供您要为其获取位置的活动,这样它可以进行优化(例如,如果某人停在某个位置,可能是location locationManager可以静默停止)。

    manager.distanceFilter = 10
    
    manager.activityType = .automotiveNavigation