QGIS/python/plugins/processing/algs/qgis/HubDistanceLines.py
Nyall Dawson b1cadb1822 Use generic algorithm icon for qgis algorithms which do not
have specific icons, instead of generic qgis icon

We consider these 'top level' algorithms, and using the
standard algorithm icon should help reflect this and
differentiate them from 3rd party algorithms.
2017-06-24 12:01:20 +10:00

153 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,
QgsFeatureSink,
QgsFeatureRequest,
QgsWkbTypes,
QgsApplication,
QgsProject,
QgsProcessingUtils)
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
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
from math import sqrt
class HubDistanceLines(QgisAlgorithm):
POINTS = 'POINTS'
HUBS = 'HUBS'
FIELD = 'FIELD'
UNIT = 'UNIT'
OUTPUT = 'OUTPUT'
UNITS = ['Meters',
'Feet',
'Miles',
'Kilometers',
'Layer units'
]
def group(self):
return self.tr('Vector analysis tools')
def __init__(self):
super().__init__()
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 name(self):
return 'distancetonearesthublinetohub'
def displayName(self):
return self.tr('Distance to nearest hub (line to hub)')
def processAlgorithm(self, parameters, context, feedback):
layerPoints = QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.POINTS), context)
layerHubs = 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 = QgsProcessingUtils.createSpatialIndex(layerHubs, context)
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 / layerPoints.featureCount() if layerPoints.featureCount() else 0
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, QgsFeatureSink.FastInsert)
feedback.setProgress(int(current * total))
del writer