mirror of
https://github.com/qgis/QGIS.git
synced 2025-03-09 00:35:20 -05:00
Algorithms and other processing code should use this method (instead of dataobjects.getLayerFromString) to retrieve layers from a string, as it considers the processing context and allows resolving strings to temporarily stored layers. This permits processing models to function correctly when intermediate results are stored as memory layers. Subsequent model algorithms can then access these temporary layers as inputs. All temporary layers will be removed when the context object is destroyed after the model algorithm is run.
157 lines
6.0 KiB
Python
157 lines
6.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
***************************************************************************
|
|
HubDistanceLines.py
|
|
---------------------
|
|
Date : May 2010
|
|
Copyright : (C) 2010 by Michael Minn
|
|
Email : pyqgis at michaelminn dot com
|
|
***************************************************************************
|
|
* *
|
|
* This program is free software; you can redistribute it and/or modify *
|
|
* it under the terms of the GNU General Public License as published by *
|
|
* the Free Software Foundation; either version 2 of the License, or *
|
|
* (at your option) any later version. *
|
|
* *
|
|
***************************************************************************
|
|
"""
|
|
from builtins import next
|
|
|
|
__author__ = 'Michael Minn'
|
|
__date__ = 'May 2010'
|
|
__copyright__ = '(C) 2010, Michael Minn'
|
|
|
|
# This will get replaced with a git SHA1 when you do a git archive
|
|
|
|
__revision__ = '$Format:%H$'
|
|
|
|
from qgis.PyQt.QtCore import QVariant
|
|
from qgis.core import (QgsField,
|
|
QgsGeometry,
|
|
QgsDistanceArea,
|
|
QgsFeature,
|
|
QgsFeatureRequest,
|
|
QgsWkbTypes,
|
|
QgsApplication,
|
|
QgsProject,
|
|
QgsProcessingUtils)
|
|
from processing.core.GeoAlgorithm import GeoAlgorithm
|
|
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
|
|
from processing.core.parameters import ParameterVector
|
|
from processing.core.parameters import ParameterTableField
|
|
from processing.core.parameters import ParameterSelection
|
|
from processing.core.outputs import OutputVector
|
|
|
|
from processing.tools import dataobjects, vector
|
|
|
|
from math import sqrt
|
|
|
|
|
|
class HubDistanceLines(GeoAlgorithm):
|
|
POINTS = 'POINTS'
|
|
HUBS = 'HUBS'
|
|
FIELD = 'FIELD'
|
|
UNIT = 'UNIT'
|
|
OUTPUT = 'OUTPUT'
|
|
|
|
UNITS = ['Meters',
|
|
'Feet',
|
|
'Miles',
|
|
'Kilometers',
|
|
'Layer units'
|
|
]
|
|
|
|
def icon(self):
|
|
return QgsApplication.getThemeIcon("/providerQgis.svg")
|
|
|
|
def svgIconPath(self):
|
|
return QgsApplication.iconPath("providerQgis.svg")
|
|
|
|
def group(self):
|
|
return self.tr('Vector analysis tools')
|
|
|
|
def name(self):
|
|
return 'distancetonearesthublinetohub'
|
|
|
|
def displayName(self):
|
|
return self.tr('Distance to nearest hub (line to hub)')
|
|
|
|
def defineCharacteristics(self):
|
|
self.units = [self.tr('Meters'),
|
|
self.tr('Feet'),
|
|
self.tr('Miles'),
|
|
self.tr('Kilometers'),
|
|
self.tr('Layer units')]
|
|
|
|
self.addParameter(ParameterVector(self.POINTS,
|
|
self.tr('Source points layer')))
|
|
self.addParameter(ParameterVector(self.HUBS,
|
|
self.tr('Destination hubs layer')))
|
|
self.addParameter(ParameterTableField(self.FIELD,
|
|
self.tr('Hub layer name attribute'), self.HUBS))
|
|
self.addParameter(ParameterSelection(self.UNIT,
|
|
self.tr('Measurement unit'), self.units))
|
|
|
|
self.addOutput(OutputVector(self.OUTPUT, self.tr('Hub distance'), datatype=[dataobjects.TYPE_VECTOR_LINE]))
|
|
|
|
def processAlgorithm(self, context, feedback):
|
|
layerPoints = dataobjects.QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.POINTS), context)
|
|
layerHubs = dataobjects.QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.HUBS), context)
|
|
fieldName = self.getParameterValue(self.FIELD)
|
|
|
|
units = self.UNITS[self.getParameterValue(self.UNIT)]
|
|
|
|
if layerPoints.source() == layerHubs.source():
|
|
raise GeoAlgorithmExecutionException(
|
|
self.tr('Same layer given for both hubs and spokes'))
|
|
|
|
fields = layerPoints.fields()
|
|
fields.append(QgsField('HubName', QVariant.String))
|
|
fields.append(QgsField('HubDist', QVariant.Double))
|
|
|
|
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields, QgsWkbTypes.LineString, layerPoints.crs(),
|
|
context)
|
|
|
|
index = vector.spatialindex(layerHubs)
|
|
|
|
distance = QgsDistanceArea()
|
|
distance.setSourceCrs(layerPoints.crs())
|
|
distance.setEllipsoid(QgsProject.instance().ellipsoid())
|
|
|
|
# Scan source points, find nearest hub, and write to output file
|
|
features = QgsProcessingUtils.getFeatures(layerPoints, context)
|
|
total = 100.0 / QgsProcessingUtils.featureCount(layerPoints, context)
|
|
for current, f in enumerate(features):
|
|
src = f.geometry().boundingBox().center()
|
|
|
|
neighbors = index.nearestNeighbor(src, 1)
|
|
ft = next(layerHubs.getFeatures(QgsFeatureRequest().setFilterFid(neighbors[0]).setSubsetOfAttributes([fieldName], layerHubs.fields())))
|
|
closest = ft.geometry().boundingBox().center()
|
|
hubDist = distance.measureLine(src, closest)
|
|
|
|
attributes = f.attributes()
|
|
attributes.append(ft[fieldName])
|
|
if units == 'Feet':
|
|
attributes.append(hubDist * 3.2808399)
|
|
elif units == 'Miles':
|
|
attributes.append(hubDist * 0.000621371192)
|
|
elif units == 'Kilometers':
|
|
attributes.append(hubDist / 1000.0)
|
|
elif units != 'Meters':
|
|
attributes.append(sqrt(
|
|
pow(src.x() - closest.x(), 2.0) +
|
|
pow(src.y() - closest.y(), 2.0)))
|
|
else:
|
|
attributes.append(hubDist)
|
|
|
|
feat = QgsFeature()
|
|
feat.setAttributes(attributes)
|
|
|
|
feat.setGeometry(QgsGeometry.fromPolyline([src, closest]))
|
|
|
|
writer.addFeature(feat)
|
|
feedback.setProgress(int(current * total))
|
|
|
|
del writer
|