如何在阵列位置找到距离当前位置最近的位置

时间:2016-04-07 17:01:37

标签: swift mapkit

我想找到离我当前位置最近的ATM,然后在地图上绘制一条路线,这是我尝试过的:

func findTheClosestATM() {
        var distances = [Double]()
        for atm in atms {
            let distance = currentLocation.distanceFromLocation(CLLocation(latitude: CLLocationDegrees(atm.latitude!), longitude: CLLocationDegrees(atm.latitude!)))

            distances.append(distance)
        }
        var closestATM = atms[0]
        closestATM = atms[distances.indexOf(distances.minElement()!)!]
        drawRouteOnMap(sourceLocation: currentLocation, destinationLocation: CLLocation(latitude: CLLocationDegrees(closestATM.latitude!), longitude: CLLocationDegrees(closestATM.latitude!)))
    }

func drawRouteOnMap(sourceLocation sourceLocation: CLLocation, destinationLocation: CLLocation) {
        mapView.removeOverlays(mapView.overlays)
        drawMapActivated = true
        let sourcePlacemark = MKPlacemark(coordinate: sourceLocation.coordinate, addressDictionary: nil)
        let destinationPlacemark = MKPlacemark(coordinate: destinationLocation.coordinate, addressDictionary: nil)

        let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
        let destinationMapItem = MKMapItem(placemark: destinationPlacemark)

        let destinationAnnotation = MKPointAnnotation()
        destinationAnnotation.title = "ATM"

        if let location = destinationPlacemark.location {
            destinationAnnotation.coordinate = location.coordinate
        }

        self.mapView.showAnnotations([destinationAnnotation], animated: true)

        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceMapItem
        directionRequest.destination = destinationMapItem
        directionRequest.transportType = .Automobile

        let directions = MKDirections(request: directionRequest)

        directions.calculateDirectionsWithCompletionHandler {
            (response, error) -> Void in

            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }

                return
            }

            let route = response.routes[0]
            self.mapView.addOverlay((route.polyline), level: MKOverlayLevel.AboveRoads)

            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }

    }

但它显示错误:

  

错误:错误域= MKErrorDomain代码= 5"方向不可用"   UserInfo = {NSLocalizedFailureReason =从其到达目的地的路线   最近的道路无法确定,MKErrorGEOError = -403,   MKErrorGEOErrorUserInfo = {},MKDirectionsErrorCode = 7,   NSLocalizedDescription =方向不可用}

我在drawRouteOnMap()的其他函数中完美地绘制它,但在findTheClosestATM()中,它不起作用。

0 个答案:

没有答案