Creating closest distance line between points and lines in QGISImproving our spatial data by calculating “Close to Coastline”, “Close to Park”, “Close to Stadium” etcCreating new lines along specifically selected existing lines using QGIS?QGIS distance from points to nearest lineError 000725 using Points to LineDraw a perpendicular line between point and line layerMinimum distance from points to nearest line among multiple lines shapefileAligning multiple points to line in QGIS?Create a perpendicular line of points to another lineDistance between reference point to many Points along a lineHow to draw all possible lines between a set of points in QGIS?Creating line from points in QGIS

I got the following comment from a reputed math journal. What does it mean?

Is honey really a supersaturated solution? Does heating to un-crystalize redissolve it or melt it?

ERC721: How to get the owned tokens of an address

Different outputs for `w`, `who`, `whoami` and `id`

What options are left, if Britain cannot decide?

Happy pi day, everyone!

How to terminate ping <dest> &

Can I use USB data pins as a power source?

Print a physical multiplication table

Why Choose Less Effective Armour Types?

Relationship between sampajanna definitions in SN 47.2 and SN 47.35

How do I hide Chekhov's Gun?

How to write cleanly even if my character uses expletive language?

About the actual radiative impact of greenhouse gas emission over time

Do the common programs (for example: "ls", "cat") in Linux and BSD come from the same source code?

How to get the n-th line after a grepped one?

Min function accepting varying number of arguments in C++17

While on vacation my taxi took a longer route, possibly to scam me out of money. How can I deal with this?

World War I as a war of liberals against authoritarians?

Professor being mistaken for a grad student

Is "upgrade" the right word to use in this context?

How to make healing in an exploration game interesting

Does multi-classing into Fighter give you heavy armor proficiency?

Are ETF trackers fundamentally better than individual stocks?



Creating closest distance line between points and lines in QGIS


Improving our spatial data by calculating “Close to Coastline”, “Close to Park”, “Close to Stadium” etcCreating new lines along specifically selected existing lines using QGIS?QGIS distance from points to nearest lineError 000725 using Points to LineDraw a perpendicular line between point and line layerMinimum distance from points to nearest line among multiple lines shapefileAligning multiple points to line in QGIS?Create a perpendicular line of points to another lineDistance between reference point to many Points along a lineHow to draw all possible lines between a set of points in QGIS?Creating line from points in QGIS













2















QGIS
I have multiple lines in one layer (trench) and multiple points in another later.



I've searched the whole Internet for a plug-in which can: connect points to the nearest line, creating a new line in a new layer.



Maybe the plug-in is already there, but I couldn't find it...



What I have:



without_lines



Desired output:



created_new_lines










share|improve this question









New contributor




Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Which software is that? QGIS or ArcGIS?

    – Taras
    Mar 12 at 7:50















2















QGIS
I have multiple lines in one layer (trench) and multiple points in another later.



I've searched the whole Internet for a plug-in which can: connect points to the nearest line, creating a new line in a new layer.



Maybe the plug-in is already there, but I couldn't find it...



What I have:



without_lines



Desired output:



created_new_lines










share|improve this question









New contributor




Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Which software is that? QGIS or ArcGIS?

    – Taras
    Mar 12 at 7:50













2












2








2








QGIS
I have multiple lines in one layer (trench) and multiple points in another later.



I've searched the whole Internet for a plug-in which can: connect points to the nearest line, creating a new line in a new layer.



Maybe the plug-in is already there, but I couldn't find it...



What I have:



without_lines



Desired output:



created_new_lines










share|improve this question









New contributor




Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












QGIS
I have multiple lines in one layer (trench) and multiple points in another later.



I've searched the whole Internet for a plug-in which can: connect points to the nearest line, creating a new line in a new layer.



Maybe the plug-in is already there, but I couldn't find it...



What I have:



without_lines



Desired output:



created_new_lines







qgis points-to-line






share|improve this question









New contributor




Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Mar 12 at 10:13









Taras

2,2742727




2,2742727






New contributor




Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Mar 12 at 7:46









Mathijs AlkemaMathijs Alkema

133




133




New contributor




Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Mathijs Alkema is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1





    Which software is that? QGIS or ArcGIS?

    – Taras
    Mar 12 at 7:50












  • 1





    Which software is that? QGIS or ArcGIS?

    – Taras
    Mar 12 at 7:50







1




1





Which software is that? QGIS or ArcGIS?

– Taras
Mar 12 at 7:50





Which software is that? QGIS or ArcGIS?

– Taras
Mar 12 at 7:50










2 Answers
2






active

oldest

votes


















2














There is not such a plugin. And if you do not want to use python, you can combine two build-in algorithms in QGIS3



I think that this answer can solve your problem: https://gis.stackexchange.com/a/280787/7849






share|improve this answer




















  • 1





    I never thought this approach is really fast. Using QGIS 2.18.xx I recommend to use the SAGA tool "Convert lines to points" in the Processing Toolbox. It takes only a few seconds to convert 1500 lines to 1.5 million points (1m spacing). And it takes only a moment to get the hub distance between 1500 points and the 1.5 million points.

    – Stefan
    2 days ago



















2














You can use the QGIS Python console for this. The output results as a memory layer. I'm using QGIS 2.18.28. Probably in QGIS 3 the code does not work, due to software changes.



Just paste this code into the Python console. You have to edit the code according to your layer names. In my case I have a shapefile points and a shapefile lines. You have to know the projection of your shapefiles and they have to have the same projection. Otherwise we have to do some transformation. Choose the right projection when adding the memory layer.



UPDATE



I've recognized that the ID of the nearest point (= line ID) was the same for every point. Now the code is updated and for every point there is the right line ID (e.g. for categorizing the data like in the picture). Additionally I've inserted a function to hide some QGIS Python console output. This reduces the running time of the code.



import math, os, sys
from contextlib import contextmanager

from operator import itemgetter

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *

import time, datetime
start_ts = time.time()

# function to hide specific QGIS output
@contextmanager
def silence_stdout():
new_target = open(os.devnull, "w")
old_target, sys.stdout = sys.stdout, new_target
try:
yield new_target
finally:
sys.stdout = old_target

# define input layer points and lines
p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0]
p_lyr.dataProvider().createSpatialIndex()
l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('roads')[0]
l_lyr.dataProvider().createSpatialIndex()
lines = [feature for feature in l_lyr.getFeatures()]

# set up memory layer for the shortest distance
d_lyr = QgsVectorLayer('LineString', 'shortestDistance', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(d_lyr)
prov = d_lyr.dataProvider()

# adding three attributes (holding point_id, road_id and the distance)
prov.addAttributes( [ QgsField("point_id", QVariant.Int), QgsField("line_id", QVariant.Int), QgsField("distance",QVariant.Int)])

# loop through all points and get the shortest distance to the next road
for i,points in enumerate(p_lyr.getFeatures()):
with silence_stdout():
# getting closest point on segment and its id from every line to a single point; getting minimum distance after sorting cswc list with itemgetter (sorting the l.geometry().closestSegmentWithContext(...) output)
# use l.id() (Python id() function) instead of l["osm_id"] when you don't have an attribute "id" describing the line data, or replace it with another attribute name
cswc = min([(l["osm_id"],l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint()))) for l in lines], key=itemgetter(1))
minDistPoint = cswc[1][1] # nearest point on line
minDistLine = cswc[0] # line id of nearest point
feat = QgsFeature()
line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])]) # creating line between point and nearest point on segment
feat.setGeometry(line)
# use point.id() (Python id() function) instead of points["id"] when you don't have an attribute "id" describing the point data, or replace it with another attribute name
feat.setAttributes([points["id"], minDistLine, line.geometry().length()])
prov.addFeatures([feat])
ts = time.time()
print i

print('Time used: sec'.format(ts - start_ts))

d_lyr.updateExtents()
d_lyr.triggerRepaint()
d_lyr.updateFields()


In a test case I have a layer with 8000 points and a layer with about 7100 lines (OSM data). It takes about 10min (i5-5500, 8GB RAM) to calculate the shortest distance layer.



enter image description here






share|improve this answer

























  • This won't work at my Qgis.. Maybe I'm doing something wrong..? Can you pm me, so I can share my shapefiles with you?

    – Mathijs Alkema
    Mar 12 at 10:05











  • Please clarify: QGIS version (2 or 3), any errors (Python console or other). Do you know how to use the Python console? See the docs docs.qgis.org/2.18/en/docs/user_manual/plugins/….

    – Stefan
    Mar 12 at 11:58











  • I am using both versions and tested in both versions.. I'm not familiar with the console... But PieterB's answer helped me out! Thanks!

    – Mathijs Alkema
    Mar 13 at 15:15











Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "79"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






Mathijs Alkema is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f315171%2fcreating-closest-distance-line-between-points-and-lines-in-qgis%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














There is not such a plugin. And if you do not want to use python, you can combine two build-in algorithms in QGIS3



I think that this answer can solve your problem: https://gis.stackexchange.com/a/280787/7849






share|improve this answer




















  • 1





    I never thought this approach is really fast. Using QGIS 2.18.xx I recommend to use the SAGA tool "Convert lines to points" in the Processing Toolbox. It takes only a few seconds to convert 1500 lines to 1.5 million points (1m spacing). And it takes only a moment to get the hub distance between 1500 points and the 1.5 million points.

    – Stefan
    2 days ago
















2














There is not such a plugin. And if you do not want to use python, you can combine two build-in algorithms in QGIS3



I think that this answer can solve your problem: https://gis.stackexchange.com/a/280787/7849






share|improve this answer




















  • 1





    I never thought this approach is really fast. Using QGIS 2.18.xx I recommend to use the SAGA tool "Convert lines to points" in the Processing Toolbox. It takes only a few seconds to convert 1500 lines to 1.5 million points (1m spacing). And it takes only a moment to get the hub distance between 1500 points and the 1.5 million points.

    – Stefan
    2 days ago














2












2








2







There is not such a plugin. And if you do not want to use python, you can combine two build-in algorithms in QGIS3



I think that this answer can solve your problem: https://gis.stackexchange.com/a/280787/7849






share|improve this answer















There is not such a plugin. And if you do not want to use python, you can combine two build-in algorithms in QGIS3



I think that this answer can solve your problem: https://gis.stackexchange.com/a/280787/7849







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 12 at 9:07

























answered Mar 12 at 8:59









PieterBPieterB

2,5331126




2,5331126







  • 1





    I never thought this approach is really fast. Using QGIS 2.18.xx I recommend to use the SAGA tool "Convert lines to points" in the Processing Toolbox. It takes only a few seconds to convert 1500 lines to 1.5 million points (1m spacing). And it takes only a moment to get the hub distance between 1500 points and the 1.5 million points.

    – Stefan
    2 days ago













  • 1





    I never thought this approach is really fast. Using QGIS 2.18.xx I recommend to use the SAGA tool "Convert lines to points" in the Processing Toolbox. It takes only a few seconds to convert 1500 lines to 1.5 million points (1m spacing). And it takes only a moment to get the hub distance between 1500 points and the 1.5 million points.

    – Stefan
    2 days ago








1




1





I never thought this approach is really fast. Using QGIS 2.18.xx I recommend to use the SAGA tool "Convert lines to points" in the Processing Toolbox. It takes only a few seconds to convert 1500 lines to 1.5 million points (1m spacing). And it takes only a moment to get the hub distance between 1500 points and the 1.5 million points.

– Stefan
2 days ago






I never thought this approach is really fast. Using QGIS 2.18.xx I recommend to use the SAGA tool "Convert lines to points" in the Processing Toolbox. It takes only a few seconds to convert 1500 lines to 1.5 million points (1m spacing). And it takes only a moment to get the hub distance between 1500 points and the 1.5 million points.

– Stefan
2 days ago














2














You can use the QGIS Python console for this. The output results as a memory layer. I'm using QGIS 2.18.28. Probably in QGIS 3 the code does not work, due to software changes.



Just paste this code into the Python console. You have to edit the code according to your layer names. In my case I have a shapefile points and a shapefile lines. You have to know the projection of your shapefiles and they have to have the same projection. Otherwise we have to do some transformation. Choose the right projection when adding the memory layer.



UPDATE



I've recognized that the ID of the nearest point (= line ID) was the same for every point. Now the code is updated and for every point there is the right line ID (e.g. for categorizing the data like in the picture). Additionally I've inserted a function to hide some QGIS Python console output. This reduces the running time of the code.



import math, os, sys
from contextlib import contextmanager

from operator import itemgetter

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *

import time, datetime
start_ts = time.time()

# function to hide specific QGIS output
@contextmanager
def silence_stdout():
new_target = open(os.devnull, "w")
old_target, sys.stdout = sys.stdout, new_target
try:
yield new_target
finally:
sys.stdout = old_target

# define input layer points and lines
p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0]
p_lyr.dataProvider().createSpatialIndex()
l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('roads')[0]
l_lyr.dataProvider().createSpatialIndex()
lines = [feature for feature in l_lyr.getFeatures()]

# set up memory layer for the shortest distance
d_lyr = QgsVectorLayer('LineString', 'shortestDistance', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(d_lyr)
prov = d_lyr.dataProvider()

# adding three attributes (holding point_id, road_id and the distance)
prov.addAttributes( [ QgsField("point_id", QVariant.Int), QgsField("line_id", QVariant.Int), QgsField("distance",QVariant.Int)])

# loop through all points and get the shortest distance to the next road
for i,points in enumerate(p_lyr.getFeatures()):
with silence_stdout():
# getting closest point on segment and its id from every line to a single point; getting minimum distance after sorting cswc list with itemgetter (sorting the l.geometry().closestSegmentWithContext(...) output)
# use l.id() (Python id() function) instead of l["osm_id"] when you don't have an attribute "id" describing the line data, or replace it with another attribute name
cswc = min([(l["osm_id"],l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint()))) for l in lines], key=itemgetter(1))
minDistPoint = cswc[1][1] # nearest point on line
minDistLine = cswc[0] # line id of nearest point
feat = QgsFeature()
line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])]) # creating line between point and nearest point on segment
feat.setGeometry(line)
# use point.id() (Python id() function) instead of points["id"] when you don't have an attribute "id" describing the point data, or replace it with another attribute name
feat.setAttributes([points["id"], minDistLine, line.geometry().length()])
prov.addFeatures([feat])
ts = time.time()
print i

print('Time used: sec'.format(ts - start_ts))

d_lyr.updateExtents()
d_lyr.triggerRepaint()
d_lyr.updateFields()


In a test case I have a layer with 8000 points and a layer with about 7100 lines (OSM data). It takes about 10min (i5-5500, 8GB RAM) to calculate the shortest distance layer.



enter image description here






share|improve this answer

























  • This won't work at my Qgis.. Maybe I'm doing something wrong..? Can you pm me, so I can share my shapefiles with you?

    – Mathijs Alkema
    Mar 12 at 10:05











  • Please clarify: QGIS version (2 or 3), any errors (Python console or other). Do you know how to use the Python console? See the docs docs.qgis.org/2.18/en/docs/user_manual/plugins/….

    – Stefan
    Mar 12 at 11:58











  • I am using both versions and tested in both versions.. I'm not familiar with the console... But PieterB's answer helped me out! Thanks!

    – Mathijs Alkema
    Mar 13 at 15:15
















2














You can use the QGIS Python console for this. The output results as a memory layer. I'm using QGIS 2.18.28. Probably in QGIS 3 the code does not work, due to software changes.



Just paste this code into the Python console. You have to edit the code according to your layer names. In my case I have a shapefile points and a shapefile lines. You have to know the projection of your shapefiles and they have to have the same projection. Otherwise we have to do some transformation. Choose the right projection when adding the memory layer.



UPDATE



I've recognized that the ID of the nearest point (= line ID) was the same for every point. Now the code is updated and for every point there is the right line ID (e.g. for categorizing the data like in the picture). Additionally I've inserted a function to hide some QGIS Python console output. This reduces the running time of the code.



import math, os, sys
from contextlib import contextmanager

from operator import itemgetter

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *

import time, datetime
start_ts = time.time()

# function to hide specific QGIS output
@contextmanager
def silence_stdout():
new_target = open(os.devnull, "w")
old_target, sys.stdout = sys.stdout, new_target
try:
yield new_target
finally:
sys.stdout = old_target

# define input layer points and lines
p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0]
p_lyr.dataProvider().createSpatialIndex()
l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('roads')[0]
l_lyr.dataProvider().createSpatialIndex()
lines = [feature for feature in l_lyr.getFeatures()]

# set up memory layer for the shortest distance
d_lyr = QgsVectorLayer('LineString', 'shortestDistance', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(d_lyr)
prov = d_lyr.dataProvider()

# adding three attributes (holding point_id, road_id and the distance)
prov.addAttributes( [ QgsField("point_id", QVariant.Int), QgsField("line_id", QVariant.Int), QgsField("distance",QVariant.Int)])

# loop through all points and get the shortest distance to the next road
for i,points in enumerate(p_lyr.getFeatures()):
with silence_stdout():
# getting closest point on segment and its id from every line to a single point; getting minimum distance after sorting cswc list with itemgetter (sorting the l.geometry().closestSegmentWithContext(...) output)
# use l.id() (Python id() function) instead of l["osm_id"] when you don't have an attribute "id" describing the line data, or replace it with another attribute name
cswc = min([(l["osm_id"],l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint()))) for l in lines], key=itemgetter(1))
minDistPoint = cswc[1][1] # nearest point on line
minDistLine = cswc[0] # line id of nearest point
feat = QgsFeature()
line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])]) # creating line between point and nearest point on segment
feat.setGeometry(line)
# use point.id() (Python id() function) instead of points["id"] when you don't have an attribute "id" describing the point data, or replace it with another attribute name
feat.setAttributes([points["id"], minDistLine, line.geometry().length()])
prov.addFeatures([feat])
ts = time.time()
print i

print('Time used: sec'.format(ts - start_ts))

d_lyr.updateExtents()
d_lyr.triggerRepaint()
d_lyr.updateFields()


In a test case I have a layer with 8000 points and a layer with about 7100 lines (OSM data). It takes about 10min (i5-5500, 8GB RAM) to calculate the shortest distance layer.



enter image description here






share|improve this answer

























  • This won't work at my Qgis.. Maybe I'm doing something wrong..? Can you pm me, so I can share my shapefiles with you?

    – Mathijs Alkema
    Mar 12 at 10:05











  • Please clarify: QGIS version (2 or 3), any errors (Python console or other). Do you know how to use the Python console? See the docs docs.qgis.org/2.18/en/docs/user_manual/plugins/….

    – Stefan
    Mar 12 at 11:58











  • I am using both versions and tested in both versions.. I'm not familiar with the console... But PieterB's answer helped me out! Thanks!

    – Mathijs Alkema
    Mar 13 at 15:15














2












2








2







You can use the QGIS Python console for this. The output results as a memory layer. I'm using QGIS 2.18.28. Probably in QGIS 3 the code does not work, due to software changes.



Just paste this code into the Python console. You have to edit the code according to your layer names. In my case I have a shapefile points and a shapefile lines. You have to know the projection of your shapefiles and they have to have the same projection. Otherwise we have to do some transformation. Choose the right projection when adding the memory layer.



UPDATE



I've recognized that the ID of the nearest point (= line ID) was the same for every point. Now the code is updated and for every point there is the right line ID (e.g. for categorizing the data like in the picture). Additionally I've inserted a function to hide some QGIS Python console output. This reduces the running time of the code.



import math, os, sys
from contextlib import contextmanager

from operator import itemgetter

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *

import time, datetime
start_ts = time.time()

# function to hide specific QGIS output
@contextmanager
def silence_stdout():
new_target = open(os.devnull, "w")
old_target, sys.stdout = sys.stdout, new_target
try:
yield new_target
finally:
sys.stdout = old_target

# define input layer points and lines
p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0]
p_lyr.dataProvider().createSpatialIndex()
l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('roads')[0]
l_lyr.dataProvider().createSpatialIndex()
lines = [feature for feature in l_lyr.getFeatures()]

# set up memory layer for the shortest distance
d_lyr = QgsVectorLayer('LineString', 'shortestDistance', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(d_lyr)
prov = d_lyr.dataProvider()

# adding three attributes (holding point_id, road_id and the distance)
prov.addAttributes( [ QgsField("point_id", QVariant.Int), QgsField("line_id", QVariant.Int), QgsField("distance",QVariant.Int)])

# loop through all points and get the shortest distance to the next road
for i,points in enumerate(p_lyr.getFeatures()):
with silence_stdout():
# getting closest point on segment and its id from every line to a single point; getting minimum distance after sorting cswc list with itemgetter (sorting the l.geometry().closestSegmentWithContext(...) output)
# use l.id() (Python id() function) instead of l["osm_id"] when you don't have an attribute "id" describing the line data, or replace it with another attribute name
cswc = min([(l["osm_id"],l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint()))) for l in lines], key=itemgetter(1))
minDistPoint = cswc[1][1] # nearest point on line
minDistLine = cswc[0] # line id of nearest point
feat = QgsFeature()
line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])]) # creating line between point and nearest point on segment
feat.setGeometry(line)
# use point.id() (Python id() function) instead of points["id"] when you don't have an attribute "id" describing the point data, or replace it with another attribute name
feat.setAttributes([points["id"], minDistLine, line.geometry().length()])
prov.addFeatures([feat])
ts = time.time()
print i

print('Time used: sec'.format(ts - start_ts))

d_lyr.updateExtents()
d_lyr.triggerRepaint()
d_lyr.updateFields()


In a test case I have a layer with 8000 points and a layer with about 7100 lines (OSM data). It takes about 10min (i5-5500, 8GB RAM) to calculate the shortest distance layer.



enter image description here






share|improve this answer















You can use the QGIS Python console for this. The output results as a memory layer. I'm using QGIS 2.18.28. Probably in QGIS 3 the code does not work, due to software changes.



Just paste this code into the Python console. You have to edit the code according to your layer names. In my case I have a shapefile points and a shapefile lines. You have to know the projection of your shapefiles and they have to have the same projection. Otherwise we have to do some transformation. Choose the right projection when adding the memory layer.



UPDATE



I've recognized that the ID of the nearest point (= line ID) was the same for every point. Now the code is updated and for every point there is the right line ID (e.g. for categorizing the data like in the picture). Additionally I've inserted a function to hide some QGIS Python console output. This reduces the running time of the code.



import math, os, sys
from contextlib import contextmanager

from operator import itemgetter

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *

import time, datetime
start_ts = time.time()

# function to hide specific QGIS output
@contextmanager
def silence_stdout():
new_target = open(os.devnull, "w")
old_target, sys.stdout = sys.stdout, new_target
try:
yield new_target
finally:
sys.stdout = old_target

# define input layer points and lines
p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0]
p_lyr.dataProvider().createSpatialIndex()
l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('roads')[0]
l_lyr.dataProvider().createSpatialIndex()
lines = [feature for feature in l_lyr.getFeatures()]

# set up memory layer for the shortest distance
d_lyr = QgsVectorLayer('LineString', 'shortestDistance', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(d_lyr)
prov = d_lyr.dataProvider()

# adding three attributes (holding point_id, road_id and the distance)
prov.addAttributes( [ QgsField("point_id", QVariant.Int), QgsField("line_id", QVariant.Int), QgsField("distance",QVariant.Int)])

# loop through all points and get the shortest distance to the next road
for i,points in enumerate(p_lyr.getFeatures()):
with silence_stdout():
# getting closest point on segment and its id from every line to a single point; getting minimum distance after sorting cswc list with itemgetter (sorting the l.geometry().closestSegmentWithContext(...) output)
# use l.id() (Python id() function) instead of l["osm_id"] when you don't have an attribute "id" describing the line data, or replace it with another attribute name
cswc = min([(l["osm_id"],l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint()))) for l in lines], key=itemgetter(1))
minDistPoint = cswc[1][1] # nearest point on line
minDistLine = cswc[0] # line id of nearest point
feat = QgsFeature()
line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])]) # creating line between point and nearest point on segment
feat.setGeometry(line)
# use point.id() (Python id() function) instead of points["id"] when you don't have an attribute "id" describing the point data, or replace it with another attribute name
feat.setAttributes([points["id"], minDistLine, line.geometry().length()])
prov.addFeatures([feat])
ts = time.time()
print i

print('Time used: sec'.format(ts - start_ts))

d_lyr.updateExtents()
d_lyr.triggerRepaint()
d_lyr.updateFields()


In a test case I have a layer with 8000 points and a layer with about 7100 lines (OSM data). It takes about 10min (i5-5500, 8GB RAM) to calculate the shortest distance layer.



enter image description here







share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago

























answered Mar 12 at 8:44









StefanStefan

2,67912042




2,67912042












  • This won't work at my Qgis.. Maybe I'm doing something wrong..? Can you pm me, so I can share my shapefiles with you?

    – Mathijs Alkema
    Mar 12 at 10:05











  • Please clarify: QGIS version (2 or 3), any errors (Python console or other). Do you know how to use the Python console? See the docs docs.qgis.org/2.18/en/docs/user_manual/plugins/….

    – Stefan
    Mar 12 at 11:58











  • I am using both versions and tested in both versions.. I'm not familiar with the console... But PieterB's answer helped me out! Thanks!

    – Mathijs Alkema
    Mar 13 at 15:15


















  • This won't work at my Qgis.. Maybe I'm doing something wrong..? Can you pm me, so I can share my shapefiles with you?

    – Mathijs Alkema
    Mar 12 at 10:05











  • Please clarify: QGIS version (2 or 3), any errors (Python console or other). Do you know how to use the Python console? See the docs docs.qgis.org/2.18/en/docs/user_manual/plugins/….

    – Stefan
    Mar 12 at 11:58











  • I am using both versions and tested in both versions.. I'm not familiar with the console... But PieterB's answer helped me out! Thanks!

    – Mathijs Alkema
    Mar 13 at 15:15

















This won't work at my Qgis.. Maybe I'm doing something wrong..? Can you pm me, so I can share my shapefiles with you?

– Mathijs Alkema
Mar 12 at 10:05





This won't work at my Qgis.. Maybe I'm doing something wrong..? Can you pm me, so I can share my shapefiles with you?

– Mathijs Alkema
Mar 12 at 10:05













Please clarify: QGIS version (2 or 3), any errors (Python console or other). Do you know how to use the Python console? See the docs docs.qgis.org/2.18/en/docs/user_manual/plugins/….

– Stefan
Mar 12 at 11:58





Please clarify: QGIS version (2 or 3), any errors (Python console or other). Do you know how to use the Python console? See the docs docs.qgis.org/2.18/en/docs/user_manual/plugins/….

– Stefan
Mar 12 at 11:58













I am using both versions and tested in both versions.. I'm not familiar with the console... But PieterB's answer helped me out! Thanks!

– Mathijs Alkema
Mar 13 at 15:15






I am using both versions and tested in both versions.. I'm not familiar with the console... But PieterB's answer helped me out! Thanks!

– Mathijs Alkema
Mar 13 at 15:15











Mathijs Alkema is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















Mathijs Alkema is a new contributor. Be nice, and check out our Code of Conduct.












Mathijs Alkema is a new contributor. Be nice, and check out our Code of Conduct.











Mathijs Alkema is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f315171%2fcreating-closest-distance-line-between-points-and-lines-in-qgis%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Lowndes Grove History Architecture References Navigation menu32°48′6″N 79°57′58″W / 32.80167°N 79.96611°W / 32.80167; -79.9661132°48′6″N 79°57′58″W / 32.80167°N 79.96611°W / 32.80167; -79.9661178002500"National Register Information System"Historic houses of South Carolina"Lowndes Grove""+32° 48' 6.00", −79° 57' 58.00""Lowndes Grove, Charleston County (260 St. Margaret St., Charleston)""Lowndes Grove"The Charleston ExpositionIt Happened in South Carolina"Lowndes Grove (House), Saint Margaret Street & Sixth Avenue, Charleston, Charleston County, SC(Photographs)"Plantations of the Carolina Low Countrye

random experiment with two different functions on unit interval Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)Random variable and probability space notionsRandom Walk with EdgesFinding functions where the increase over a random interval is Poisson distributedNumber of days until dayCan an observed event in fact be of zero probability?Unit random processmodels of coins and uniform distributionHow to get the number of successes given $n$ trials , probability $P$ and a random variable $X$Absorbing Markov chain in a computer. Is “almost every” turned into always convergence in computer executions?Stopped random walk is not uniformly integrable

How should I support this large drywall patch? Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?How do I cover large gaps in drywall?How do I keep drywall around a patch from crumbling?Can I glue a second layer of drywall?How to patch long strip on drywall?Large drywall patch: how to avoid bulging seams?Drywall Mesh Patch vs. Bulge? To remove or not to remove?How to fix this drywall job?Prep drywall before backsplashWhat's the best way to fix this horrible drywall patch job?Drywall patching using 3M Patch Plus Primer