МК Полилина не рисует на карте. Как я могу решить эту проблему? - PullRequest
0 голосов
/ 23 апреля 2019

Я пытаюсь нарисовать MKPolyline на карте. Когда я выполняю симуляцию в приложении, местоположение перемещается правильно, но линия не рисуется. Как я могу решить эту проблему?

    mapView.delegate = self
    mapView.showsUserLocation = true
    mapView.mapType = MKMapType(rawValue: 0)!
    mapView.userTrackingMode = MKUserTrackingMode(rawValue: 2)!
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    mapView.mapType = MKMapType(rawValue: 0)!
}

override func viewWillAppear(_ animated: Bool) {
    locationManager.startUpdatingHeading()
    locationManager.startUpdatingLocation()
}

override func viewWillDisappear(_ animated: Bool) {
    locationManager.stopUpdatingHeading()
    locationManager.stopUpdatingLocation()
}

// MARK: - CLLocationManager delegate

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
    //drawing path or route covered
    if let oldLocationNew = oldLocation as CLLocation?{
        let oldCoordinates = oldLocationNew.coordinate
        let newCoordinates = newLocation.coordinate
        var area = [oldCoordinates, newCoordinates]
        var polyline = MKPolyline(coordinates: &area, count: area.count)
        mapView.add(polyline)
    }

    //calculation for location selection for pointing annoation
    if let previousLocationNew = previousLocation as CLLocation?{
        //case if previous location exists
        if previousLocation.distance(from: newLocation) > 200 {
            addAnnotationsOnMap(locationToPoint: newLocation)
            previousLocation = newLocation
        }
    }
    else{
        //case if previous location doesn't exists
        addAnnotationsOnMap(locationToPoint: newLocation)
        previousLocation = newLocation
    }
}

// MARK: - MKMapView delegate

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

    if (overlay is MKPolyline) {
        var pr = MKPolylineRenderer(overlay: overlay)
        pr.strokeColor = UIColor.red
        pr.lineWidth = 5
        return pr
    }

    return nil
}


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if startDate == nil {
        startDate = Date()
    } else {
        print("elapsedTime:", String(format: "%.0fs", Date().timeIntervalSince(startDate)))
        timeLabel.text="\(Date().timeIntervalSince(startDate))"
    }
    if startLocation == nil {
        startLocation = locations.first
    } else if let location = locations.last {
        traveledDistance += lastLocation.distance(from: location)
        print("Traveled Distance:",  traveledDistance)
        distanceLabel.text="\(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()
    }
}

MKPolyline должно быть нарисовано при перемещении пользователя.

1 Ответ

0 голосов
/ 24 апреля 2019

Подпись для mapView(_:rendererFor:) неверна.Это изменилось.Теперь это:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = .red
        renderer.lineWidth = 5
        return renderer
    }

    fatalError("Unexpected MKOverlay type")
}

Если вы добавите оператор или точку останова print в ваш текущий метод, я думаю, вы обнаружите, что он не вызывается.И, конечно же, убедитесь, что вы установили delegate вида вашей карты, либо в IB, либо программно.


Кстати, у вас есть похожая проблема с didUpdateToLocation.Подпись этого теперь:

func locationManager(_ manager: CLLocationManager, 
       didUpdateTo newLocation: CLLocation, 
              from oldLocation: CLLocation) { 
    ...
}

Но вы действительно не должны использовать этот метод вообще.Как видно из документации , она устарела.Используйте взамен locationManager(_:didUpdateLocations:).Вам нужно будет сохранить собственную ссылку на oldLocation

var oldLocation: CLLocation?

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last else { return }

    if let oldCoordinate = oldLocation?.coordinate {
        let coordinates = [oldCoordinate, location.coordinate]
        let polyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
        mapView.addOverlay(polyline)
    }

    oldLocation = location

    ...
}
...