87 lines
2.8 KiB
Python
87 lines
2.8 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import time
|
|
from typing import Optional, Tuple
|
|
|
|
from qgis.core import (
|
|
QgsCoordinateReferenceSystem,
|
|
QgsCoordinateTransform,
|
|
QgsProject,
|
|
QgsVectorFileWriter,
|
|
QgsVectorLayer,
|
|
)
|
|
|
|
from . import layers, upload
|
|
from .errors import GeoDonkeyError
|
|
from .i18n import tr
|
|
from .mapcontext import WGS84
|
|
|
|
|
|
def feature_count(layer: QgsVectorLayer, selected_only: bool = False) -> int:
|
|
if layer is None:
|
|
return 0
|
|
if selected_only:
|
|
return int(layer.selectedFeatureCount())
|
|
count = layer.featureCount()
|
|
return int(count) if count and count > 0 else 0
|
|
|
|
|
|
def _target_path(layer: QgsVectorLayer) -> str:
|
|
name = upload.filename_for(layer.name() if layer is not None else "")
|
|
return os.path.join(layers.result_folder(),
|
|
"upload-%d-%s" % (int(time.time()), name))
|
|
|
|
|
|
def layer_to_geojson(layer: QgsVectorLayer,
|
|
selected_only: bool = False,
|
|
feedback=None) -> Tuple[bytes, str]:
|
|
if layer is None:
|
|
raise GeoDonkeyError(tr("Choose a vector layer first."))
|
|
if selected_only and layer.selectedFeatureCount() <= 0:
|
|
raise GeoDonkeyError(tr("Nothing is selected in this layer."))
|
|
|
|
options = QgsVectorFileWriter.SaveVectorOptions()
|
|
options.driverName = "GeoJSON"
|
|
options.fileEncoding = "UTF-8"
|
|
options.onlySelectedFeatures = bool(selected_only)
|
|
options.ct = QgsCoordinateTransform(layer.crs(),
|
|
QgsCoordinateReferenceSystem(WGS84),
|
|
QgsProject.instance())
|
|
options.layerOptions = ["RFC7946=YES", "WRITE_NAME=NO", "COORDINATE_PRECISION=7"]
|
|
if feedback is not None:
|
|
options.feedback = feedback
|
|
|
|
path = _target_path(layer)
|
|
result = QgsVectorFileWriter.writeAsVectorFormatV3(
|
|
layer, path, QgsProject.instance().transformContext(), options)
|
|
code = result[0]
|
|
message = result[1] if len(result) > 1 else ""
|
|
if code != QgsVectorFileWriter.WriterError.NoError:
|
|
raise GeoDonkeyError(
|
|
tr("The layer could not be written as GeoJSON."),
|
|
detail="%s (%s)" % (message or code, path))
|
|
|
|
written = result[2] if len(result) > 2 and result[2] else path
|
|
try:
|
|
with open(written, "rb") as handle:
|
|
data = handle.read()
|
|
except OSError as exc:
|
|
raise GeoDonkeyError(tr("The layer could not be written as GeoJSON."),
|
|
detail="%s: %s" % (written, exc))
|
|
finally:
|
|
_remove(written)
|
|
|
|
if not data.strip():
|
|
raise GeoDonkeyError(tr("The layer has no features to upload."))
|
|
return data, upload.filename_for(layer.name())
|
|
|
|
|
|
def _remove(path: Optional[str]) -> None:
|
|
if not path:
|
|
return
|
|
try:
|
|
os.remove(path)
|
|
except OSError:
|
|
pass
|