Ejemplo n.º 1
0
 def _run(self):
     """Run the process"""
     properties = self.gather_values()
     if properties['load_only']:
         # Legacy, waiting to remove the OsmParser for QGIS >= 3.6
         # Change in osm_file_dialog.py L131 too
         output_geom_legacy = [
             layer.value.lower() for layer in properties['outputs']
         ]
         osm_parser = OsmParser(properties['osm_file'],
                                load_only=True,
                                osm_conf=properties['osm_conf'],
                                layers=output_geom_legacy)
         layers = osm_parser.processing_parse()
         for item in layers.values():
             # noinspection PyArgumentList
             QgsProject.instance().addMapLayer(item)
     elif properties['subset']:
         sql_query = self.generate_sql(properties)
         open_file(dialog=self.dialog,
                   osm_file=properties['osm_file'],
                   key=properties['key'],
                   output_geom_types=properties['outputs'],
                   output_dir=properties['output_directory'],
                   output_format=properties['output_format'],
                   prefix_file=properties['prefix_file'],
                   subset=True,
                   subset_query=sql_query)
         self.dialog.display_message_bar(tr('Successful query'),
                                         level=Qgis.Success,
                                         duration=5)
     else:
         open_file(dialog=self.dialog,
                   osm_file=properties['osm_file'],
                   output_geom_types=properties['outputs'],
                   output_dir=properties['output_directory'],
                   output_format=properties['output_format'],
                   prefix_file=properties['prefix_file'])
         self.dialog.display_message_bar(tr('Successful query'),
                                         level=Qgis.Success,
                                         duration=5)
Ejemplo n.º 2
0
    def process_road(self, context, url):
        """Major step of the process"""

        if self.feedback.isCanceled():
            self.feedback.reportError(
                'The algorithm has been canceled during the building of the url.'
            )
            return self.OUTPUT_CANCEL

        self.feedback.setCurrentStep(1)
        self.feedback.pushInfo('Downloading data and OSM file.')

        connexion_overpass_api = ConnexionOAPI(url)
        osm_file = connexion_overpass_api.run()

        if self.feedback.isCanceled():
            self.feedback.reportError(
                'The algorithm has been canceled during the download.')
            return self.OUTPUT_CANCEL

        self.feedback.setCurrentStep(2)
        self.feedback.pushInfo('Processing downloaded file.')

        out_dir = dirname(self.file) if self.file else None
        out_file = basename(self.file)[:-5] if self.file else None

        osm_parser = OsmParser(osm_file=osm_file,
                               output_format=Format.GeoPackage,
                               output_dir=out_dir,
                               prefix_file=out_file,
                               feedback_alg=True,
                               feedback=self.feedback)

        layers = osm_parser.processing_parse()

        if self.feedback.isCanceled():
            self.feedback.reportError(
                'The algorithm has been canceled during the parsing.')
            return self.OUTPUT_CANCEL

        self.feedback.setCurrentStep(7)
        self.feedback.pushInfo('Decorating the requested layers.')

        layer_output = []
        OUTPUT = {
            'points': self.OUTPUT_POINTS,
            'lines': self.OUTPUT_LINES,
            'multilinestrings': self.OUTPUT_MULTILINESTRINGS,
            'multipolygons': self.OUTPUT_MULTIPOLYGONS
        }

        for layer in layers:
            layers[layer]['layer_decorated'] = processing.run(
                "quickosm:decoratelayer",
                {'LAYER': layers[layer]['vector_layer']},
                feedback=self.feedback)
            context.temporaryLayerStore().addMapLayer(
                layers[layer]['vector_layer'])
            layer_output.append(
                QgsProcessingUtils.mapLayerFromString(
                    layers[layer]['vector_layer'].id(), context, True))
            if 'tags' in layers[layer]:
                layer_details = QgsProcessingContext.LayerDetails(
                    'OSMQuery_' + layer, context.project(), OUTPUT[layer])
                if 'colour' in layers[layer]['tags']:
                    layer_details.setPostProcessor(
                        SetColoringPostProcessor.create(layers[layer]['tags']))
                context.addLayerToLoadOnCompletion(
                    layers[layer]['vector_layer'].id(), layer_details)

        if self.feedback.isCanceled():
            self.feedback.reportError(
                'The algorithm has been canceled during the post processing.')
            return self.OUTPUT_CANCEL

        outputs = {
            self.OUTPUT_POINTS: layer_output[0].id(),
            self.OUTPUT_LINES: layer_output[1].id(),
            self.OUTPUT_MULTILINESTRINGS: layer_output[2].id(),
            self.OUTPUT_MULTIPOLYGONS: layer_output[3].id(),
        }
        return outputs
Ejemplo n.º 3
0
def open_file(dialog: QDialog = None,
              osm_file: str = None,
              output_geom_types: list = None,
              white_list_column: dict = None,
              key: Union[str, List[str]] = None,
              layer_name: str = "OsmFile",
              config_outputs: dict = None,
              output_dir: str = None,
              output_format: Format = None,
              final_query: str = None,
              prefix_file: str = None,
              subset: bool = False,
              subset_query: str = None,
              feedback: QgsFeedback = None) -> int:
    """
    Open an osm file.

    Memory layer if no output directory is set, or Geojson in the output
    directory.

    :param final_query: The query where the file comes from. Might be empty if
    it's a local OSM file.
    :type final_query: basestring
    """

    if output_geom_types is None:
        output_geom_types = OSM_LAYERS
    # Legacy, waiting to remove the OsmParser for QGIS >= 3.6
    # Change in osm_file_dialog.py L131 too
    output_geom_legacy = [geom.value.lower() for geom in output_geom_types]
    if not white_list_column:
        white_list_column = None

    LOGGER.info('The OSM file is: {}'.format(osm_file))
    if feedback:
        if feedback.isCanceled():
            return None

    # Parsing the file
    osm_parser = OsmParser(osm_file=osm_file,
                           layers=output_geom_legacy,
                           output_format=output_format,
                           output_dir=output_dir,
                           prefix_file=prefix_file,
                           layer_name=layer_name,
                           key=key,
                           white_list_column=white_list_column,
                           subset=subset,
                           subset_query=subset_query,
                           feedback=feedback)

    if dialog:
        osm_parser.signalText.connect(dialog.set_progress_text)
        osm_parser.signalPercentage.connect(dialog.set_progress_percentage)

    start_time = time.time()
    layers = osm_parser.processing_parse()
    elapsed_time = time.time() - start_time
    parser_time = time.strftime("%Hh %Mm %Ss", time.gmtime(elapsed_time))
    LOGGER.info('The OSM parser took: {}'.format(parser_time))

    if feedback:
        if feedback.isCanceled():
            return None

    # Finishing the process with an output format or memory layer
    num_layers = 0

    for i, (layer, item) in enumerate(layers.items()):
        if dialog:
            dialog.set_progress_percentage(i / len(layers) * 100)
        QApplication.processEvents()
        if item['featureCount'] and (LayerType(layer.capitalize())
                                     in output_geom_types):

            final_layer_name = layer_name
            # If configOutputs is not None (from My Queries)
            if config_outputs:
                if config_outputs[layer]['namelayer']:
                    final_layer_name = config_outputs[layer]['namelayer']

            new_layer = item['vector_layer']
            new_layer.setName(final_layer_name)

            # Try to set styling if defined
            if config_outputs and config_outputs[layer]['style']:
                new_layer.loadNamedStyle(config_outputs[layer]['style'])
            else:
                if "colour" in item['tags']:
                    index = item['tags'].index('colour')
                    colors = new_layer.uniqueValues(index)
                    categories = []
                    for value in colors:
                        if str(value) == 'None':
                            value = ''
                        if layer in ['lines', 'multilinestrings']:
                            symbol = QgsSymbol.defaultSymbol(
                                QgsWkbTypes.LineGeometry)
                        elif layer == "points":
                            symbol = QgsSymbol.defaultSymbol(
                                QgsWkbTypes.PointGeometry)
                        elif layer == "multipolygons":
                            symbol = QgsSymbol.defaultSymbol(
                                QgsWkbTypes.PolygonGeometry)
                        symbol.setColor(QColor(value))
                        category = QgsRendererCategory(str(value), symbol,
                                                       str(value))
                        categories.append(category)

                    renderer = QgsCategorizedSymbolRenderer(
                        "colour", categories)
                    new_layer.setRenderer(renderer)

            # Add action about OpenStreetMap
            actions.add_actions(new_layer, item['tags'])

            QgsProject.instance().addMapLayer(new_layer)

            if final_query:
                QgsExpressionContextUtils.setLayerVariable(
                    new_layer, 'quickosm_query', final_query)
                actions.add_relaunch_action(new_layer, final_layer_name)
                if dialog:
                    dialog.iface.addCustomActionForLayer(
                        dialog.reload_action, new_layer)

            metadata = QgsLayerMetadata()
            metadata.setRights([tr("© OpenStreetMap contributors")])
            metadata.setLicenses(['https://openstreetmap.org/copyright'])
            new_layer.setMetadata(metadata)
            num_layers += 1

    return num_layers