swift2 如何在swift 2中显示MKPointAnnotation和用户当前位置之间的路线

lsmd5eda  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(162)

我试图显示MKPointAnnotation和用户当前位置之间的路线,但失败了。
我的想法是:获取用户的当前位置-〉获取MKPointAnnotation的坐标-〉与MKPolylineRenderer对齐
问题是我找不到问题所在。:(我不知道应该在哪里修改。

class MapInSearch: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
     var destination: MKMapItem?
     var coords: CLLocationCoordinate2D?
    let locationManager = CLLocationManager()

    var PlaceLat = ""
    var PlaceLong = ""// get from previous view controller

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.requestAlwaysAuthorization()

        // For use in foreground
        self.locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }// step 1 

        self.mapView.showsUserLocation = true
        self.mapView.delegate = self
       self.addRoute() // step 2
    }

    func addRoute() {
        var pointsToUse: [CLLocationCoordinate2D] = []

        if PlaceLat != "" || PlaceLong != "" {
        let coords = "\(PlaceLat), \(PlaceLong)"
        let p = CGPointFromString(coords)
        pointsToUse += [CLLocationCoordinate2DMake(CLLocationDegrees(p.x), CLLocationDegrees(p.y))]
        }
      pointsToUse += [CLLocationCoordinate2DMake(CLLocationDegrees(coords!.latitude), CLLocationDegrees(coords!.longitude))]
        let myPolyline = MKPolyline(coordinates: &pointsToUse, count: 2)
        mapView.addOverlay(myPolyline)

    }

    func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
            let lineView = MKPolylineRenderer(overlay: overlay)
            lineView.strokeColor = UIColor.greenColor()
            return lineView // step 3 
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
      self.coords = manager.location!.coordinate
        print("locations = \(coords!.latitude) \(coords!.longitude)")
    }

我的代码很乱,因为我混合了4-5个教程。而且,这些教程是用swift 1.2写的。(我试着把它编辑成swift 2,但我失败了)

qgelzfjb

qgelzfjb1#

你曾经解决过你的问题吗?使用XCode 7.3中Swift 2的最新迭代,在你的视图中(我们将称之为MyViewController):

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.mapView.delegate = self

    var coordinates : [CLLocationCoordinate2D] = [];
    addRoute(coordinates);       
}

func addRoute(coordinates: [CLLocationCoordinate2D]) {

    // insert your code to populate coordinates array with your coordinates
    polyLine = MKPolyline(coordinates: &coordinates, count: coordinates.count)
    self.mapView.addOverlay(polyLine, level: MKOverlayLevel.AboveRoads)
}

然后在同一文件中:

extension MyViewController: MKMapViewDelegate {
    func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
        let pr = MKPolylineRenderer(overlay: overlay);
        pr.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.5);
        pr.lineWidth = 5;
        return pr;
    }
}

你可能会发现重要的部分是扩展。我还没有测试过这段代码,所以请随时纠正任何悄悄出现的问题。

rqenqsqc

rqenqsqc2#

在您的CLLocationManagerDelegate委托函数didUpdateLocations中,您可以通过设置self.myLocation = locations[0] as CLLocation来更新您的位置
然后调用MakeRoute()--这是我写的一个函数,可以通过开车或步行来制定路线(因此使用self.driveIsSet

func makeRoute()  {
        let startPlaceMark = MKPlacemark(coordinate: myLocation.coordinate)
        let endPlaceMark = MKPlacemark(coordinate: restLocation.coordinate)

        let startMapItem = MKMapItem(placemark: startPlaceMark)
        let endMapItem = MKMapItem(placemark: endPlaceMark)

        let directionRequest = MKDirectionsRequest()
        directionRequest.source = startMapItem
        directionRequest.destination = endMapItem
        if self.driveIsSet {
            directionRequest.transportType = .automobile
        } else {
            directionRequest.transportType = .walking
        }

        let directions = MKDirections(request: directionRequest)
        directions.calculate { (routeResponse, routeError) in
            guard let routeResponse = routeResponse else {
                if let routeError = routeError {
                    print(routeError)
                }
                return
            }
            self.mapView.removeOverlays(self.mapView.overlays)
            let route = routeResponse.routes[0]
            self.mapView.add(route.polyline, level: .aboveRoads)
        }
    }

相关问题