Нарисуйте путь на картах Apple, используя начальную точку, конечную точку и проходя через массив точек - PullRequest
0 голосов
/ 18 июня 2019

Я работаю над приложением, в котором мне нужно нарисовать путь, куда бы пользователь ни ездил на Apple Maps.Я получаю очки, которые посетил пользователь, как массив широт и долгот, через который должен пройти нарисованный путь.Я новичок на картах Google, поэтому, пожалуйста, помогите мне.

У меня есть широта и долгота, но когда я пытался создать путь в первый раз, он напрямую прошел путь от точки A до точки B безучитывая средние баллы.Когда я попробовал другой подход, средние точки рассматривались, но линии были совершенно прямыми (прямо из точки А в среднюю точку, затем прямо в точку В, игнорируя здания и дороги.)

Код, который я пробовал:Подход 1:

func showRouteOnMapForJourneys(viaPoints: [ViaPointCoordinatesModel] ,startPoints: StartingPointCoordinatesModel, endPoints: EndingPointCoordinatesModel) {

    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: startPoints.latitude, longitude: startPoints.longitude), span: span)
    myMapView.setRegion(region, animated: true)
    myMapView.delegate = self

    let sourceLocation = CLLocationCoordinate2D(latitude: startPoints.latitude, longitude: startPoints.longitude)
    let destinationLocation = CLLocationCoordinate2D(latitude: endPoints.latitude, longitude: endPoints.longitude)
    let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
    let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
    let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
    let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
    let sourceAnnotation = MKPointAnnotation()
    sourceAnnotation.title = NSLocalizedString("Start Location", comment: "")

    if let location = sourcePlacemark.location {
        sourceAnnotation.coordinate = location.coordinate
    }

    let destinationAnnotation = MKPointAnnotation()
    destinationAnnotation.title = NSLocalizedString("End Location", comment: "")

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

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

    let start = CLLocationCoordinate2D(latitude: startPoints.latitude, longitude: startPoints.longitude)
    locations.append(start)

    for coords in viaPoints {
        let lat = Double(coords.latitude)
        let lon = Double(coords.longitude)
        let destination = CLLocationCoordinate2D(latitude: lat, longitude: lon)
        locations.append(destination)
    }

    let end = CLLocationCoordinate2D(latitude: endPoints.latitude, longitude: endPoints.longitude)
    locations.append(end)


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

    let directions = MKDirections(request: directionRequest)

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

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

        let route = response.routes[0]
        self.myMapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)
    }


}

Подход 2:

func addPolyLine(viaPoints: [ViaPointCoordinatesModel], startLatitude: Double, startLongitude: Double, endLatitude: Double, endLongitude: Double){
    locations.removeAll()
    myMapView?.delegate = self

    let sourceLocation = CLLocationCoordinate2D(latitude: startLatitude, longitude: startLongitude)
    let destinationLocation = CLLocationCoordinate2D(latitude: endLatitude, longitude: endLongitude)
    let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
    let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
    let sourceAnnotation = MKPointAnnotation()
    sourceAnnotation.title = NSLocalizedString("Start Location", comment: "")

    if let location = sourcePlacemark.location {
        sourceAnnotation.coordinate = location.coordinate
    }

    let destinationAnnotation = MKPointAnnotation()
    destinationAnnotation.title = NSLocalizedString("End Location", comment: "")

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

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

    let start = CLLocationCoordinate2D(latitude: startLatitude, longitude: startLongitude)
    locations.append(start)

    for coords in viaPoints {
        let lat = Double(coords.latitude)
        let lon = Double(coords.longitude)
        let destination = CLLocationCoordinate2D(latitude: lat, longitude: lon)
        locations.append(destination)
    }

    let end = CLLocationCoordinate2D(latitude: endLatitude, longitude: endLongitude)
    locations.append(end)

    let geodesic = MKGeodesicPolyline(coordinates: locations, count: locations.count)
    myMapView.add(geodesic)

    UIView.animate(withDuration: 1.5, animations: { () -> Void in
        let span = MKCoordinateSpanMake(0.05, 0.05)
        let region1 = MKCoordinateRegion(center: self.locations[0], span: span)
        self.myMapView.setRegion(region1, animated: true)
    })
}

Линии либо игнорируют средние точки, либо игнорируют дороги

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...