Creating a line layer that links many points in layer to one point in another layer?

In QGIS, you can use the Connect Points plugin which you can download from:

Plugins > Manage and Install Plugins...

Example:

  1. Here are a couple of layers, layer_A has a bunch of points; layer_B has one. Make sure both layers contain an integer field where the values are exactly the same (e.g. both my layers have an id field where all values are 1). The plugin uses this to connect your points. When your plugin is enabled, go to its settings:

    Interface


  1. Select the options:

    Settings


  1. Result:

    Result


Note that this plugin is experimental so you will need to enable the Show also experimental plugins option (thanks to @blue_chip):

Plugins > Manage and Install Plugins > Settings

if both of your layers are points this below query should work just plug in your own data. I did a test with creating lines from 1 layer with 150+ point rows and a layer with 1 point

drop table if exists line;
create table line as
select layer1.id ,st_makeline(layer1.geom,point.geom) as geom from layer1,point

enter image description here


Assuming to start from this situation (one point layer with one feature and one point layer with 300 features):

enter image description here

you may run this code from the Python Console (after having loaded the two layers of interest in QGIS):

from qgis.core import *
from qgis.PyQt.QtCore import QVariant

layer1 = QgsMapLayerRegistry.instance().mapLayersByName('1point')[0]
crs = layer1.crs().toWkt()
layer2 = QgsMapLayerRegistry.instance().mapLayersByName('300points')[0]

outLayer = QgsVectorLayer('Linestring?crs='+ crs, 'line_output' , 'memory')
prov = outLayer.dataProvider()
fields = layer1.pendingFields()
for field in layer2.pendingFields():
    fields.append(field)
prov.addAttributes(fields)
outLayer.updateFields()

for feature in layer1.getFeatures():
    coords = feature.geometry().asPoint()
    attr1 = feature.attributes()

    for feat in layer2.getFeatures():
        seg_start = coords
        seg_end = feat.geometry().asPoint()
        attr2 = feat.attributes()
        attrs = attr1 + attr2
        outGeom = QgsFeature()
        outGeom.setGeometry(QgsGeometry.fromPolyline([seg_start, seg_end]))
        outGeom.setAttributes(attrs)
        prov.addFeatures([outGeom])

QgsMapLayerRegistry.instance().addMapLayer(outLayer)

for obtaining this result:

enter image description here

You only need to adapt the names for the layers ('1point' and '300points') to the names with which they are loaded in the Layers Panel.

My approach will work independently from the number of features in both layers.

Tags:

Postgis

Qgis