Mapbox новый файл geoJSon не загружается - PullRequest
0 голосов
/ 24 сентября 2019

Я могу успешно загрузить geoJSonFile один раз, когда я попытался загрузить другой, он не загружается.Любая помощь с благодарностью.

Ниже мой код.

    //MARK: - Mapbox helper
    func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {
        setGeoJsonForselected(postionToLoad: DroneItemSelected)

        print("//MARK: - Mapbox helper mapViewDidFinishLoadingMap called")
        if(!Selected2D){

            if let source = style.source(withIdentifier: "composite") {
                let layer = MGLFillExtrusionStyleLayer(identifier: "buildings", source: source)
                layer.sourceLayerIdentifier = "building"

                // Filter out buildings that should not extrude.
                layer.predicate = NSPredicate(format: "extrude == 'true'")

                // Set the fill extrusion height to the value for the building height attribute.
                layer.fillExtrusionHeight = NSExpression(forKeyPath: "height")
                layer.fillExtrusionOpacity = NSExpression(forConstantValue: 0.75)
                layer.fillExtrusionColor = NSExpression(forConstantValue: UIColor.white)

                // Insert the fill extrusion layer below a POI label layer. If you aren’t sure what the layer is called, you can view the style in Mapbox Studio or iterate over the style’s layers property, printing out each layer’s identifier.
                if let symbolLayer = style.layer(withIdentifier: "poi-scalerank3") {
                    style.insertLayer(layer, below: symbolLayer)
                } else {
                    style.addLayer(layer)
                }
            }





                let idetifierToUse = NSString(format:"polyline_%d.geojson",DroneItemSelected) as String

            print ("droneitemselected at  didFinishLoading ",DroneItemSelected)


                 let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
                    let fileURL = documentDirectory!.appendingPathComponent(idetifierToUse)
            print ("fileURL at  didFinishLoading ",fileURL)

            let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
            let url = NSURL(fileURLWithPath: path)
            if let pathComponent = url.appendingPathComponent(idetifierToUse) {
                let filePath = pathComponent.path
                let fileManager = FileManager.default
                if fileManager.fileExists(atPath: filePath) {
                    print("FILE AVAILABLE")
                    guard let jsonDataNew = try? Data(contentsOf: fileURL) else {
                        preconditionFailure("Failed to parse GeoJSON file")
                    }




                    guard let shapeFromGeoJSON = try? MGLShape(data: jsonDataNew as Data, encoding: String.Encoding.utf8.rawValue) else {
                        fatalError("Could not generate MGLShape")
                    }

                    let idetifier = NSString(format:"polyline_%d", DroneItemSelected) as String

                    let source = MGLShapeSource(identifier: idetifier, shape: shapeFromGeoJSON, options: nil)
                    style.addSource(source)



                    let idetifier1 = NSString(format:"room-extrusion_%d", DroneItemSelected) as String

                    let upperlayer = MGLFillExtrusionStyleLayer(identifier: idetifier1, source: source)
                    let idetifier2 = NSString(format:"room-data_%d", DroneItemSelected) as String

                    upperlayer.sourceLayerIdentifier = idetifier2
                   // upperlayer.predicate = NSPredicate(format: "extrude == 'false'")


                    upperlayer.fillExtrusionHeight = NSExpression(forKeyPath: "height") //NSExpression(forConstantValue: 100)
                    upperlayer.fillExtrusionOpacity = NSExpression(forConstantValue: 0.75)
                    upperlayer.fillExtrusionColor = NSExpression(forKeyPath: "color")
                    upperlayer.fillExtrusionBase = NSExpression(forKeyPath: "base_height")

                    style.addLayer(upperlayer)
//                    MapBoxView.setCenter(
//                        CLLocationCoordinate2D(latitude: self.centre_val_latitude, longitude:  self.centre_val_longitude),
//                        zoomLevel: 15,
//                        animated: false)
                } else {
                    print("FILE NOT AVAILABLE")
                }
            } else {
                print("FILE PATH NOT AVAILABLE")
            }

        }else{

            print ("  Me Called  ")

            loadGeoJson()


        }

        if(self.tableDSArr.count>0){centreMapToDrone()}

        MapBoxView.setCenter(
            CLLocationCoordinate2D(latitude: self.centre_val_latitude, longitude:  self.centre_val_longitude),
            zoomLevel: 15,
            animated: false)



    }
    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {

        if let castAnnotation = annotation as? MyCustomPointAnnotation {
            if (castAnnotation.willUseImage) {
                return nil
            }
        }

        // Assign a reuse identifier to be used by both of the annotation views, taking advantage of their similarities.
        let reuseIdentifier = "reusableDotView"

        // For better performance, always try to reuse existing annotations.
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)

        // If there’s no reusable annotation view available, initialize a new one.
        if annotationView == nil {
            annotationView = MGLAnnotationView(reuseIdentifier: reuseIdentifier)
            annotationView?.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
            annotationView?.layer.cornerRadius = (annotationView?.frame.size.width)! / 2
            annotationView?.layer.borderWidth = 4.0
            annotationView?.layer.borderColor = UIColor.white.cgColor
            annotationView!.backgroundColor = UIColor(red: 0.03, green: 0.80, blue: 0.69, alpha: 1.0)
        }

        return annotationView
    }
    func loadGeoJson() {
        DispatchQueue.global().async {
            // Get the path for example.geojson in the app’s bundle.

            let idetifierToUse = NSString(format:"polyline_%d.geojson",self.DroneItemSelected) as String

            print ("droneitemselected at  didFinishLoading ",self.DroneItemSelected)


            let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
            let fileURL = documentDirectory!.appendingPathComponent(idetifierToUse)
            print ("fileURL at  loadGeoJson ",fileURL)


            guard let jsonDataNew = try? Data(contentsOf: fileURL) else {
                preconditionFailure("Failed to parse GeoJSON file")
            }


            DispatchQueue.main.async {
                self.drawPolyline(geoJson: jsonDataNew)
            }
        }
    }
    func randomString(length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
    func drawPolyline(geoJson: Data) {
        // Add our GeoJSON data to the map as an MGLGeoJSONSource.
        // We can then reference this data from an MGLStyleLayer.

        // MGLMapView.style is optional, so you must guard against it not being set.
        guard let style = MapBoxView.style else { return }

        guard let shapeFromGeoJSON = try? MGLShape(data: geoJson, encoding: String.Encoding.utf8.rawValue) else {
            fatalError("Could not generate MGLShape")
        }



        let randomIdentifier = randomString(length: 12)
        let idetifier = NSString(format:"polyline_%d", DroneItemSelected) as String

        let Esource = MGLShapeSource(identifier: "polylineE", shape: shapeFromGeoJSON, options: nil)
        style.addSource(Esource)

        // Add a layer to style our polyline.
        let layer = MGLLineStyleLayer(identifier: "polylineE", source: Esource)
        layer.lineJoin = NSExpression(forConstantValue: "round")
        layer.lineCap = NSExpression(forConstantValue: "round")
        layer.lineColor = NSExpression(forConstantValue: UIColor.red)

        // The line width should gradually increase based on the zoom level.
        layer.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)",
                                       [14: 5, 18: 20])
        style.addLayer(layer)




    }

...