Creating closest distance line between points and lines 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
    15 hours ago











  • Interesting would be the feature count of both of your layers. It looks like your using OpenStreetMap data. According to big data sets you have to think of spatial indexes.

    – Stefan
    14 hours ago
















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
    15 hours ago











  • Interesting would be the feature count of both of your layers. It looks like your using OpenStreetMap data. According to big data sets you have to think of spatial indexes.

    – Stefan
    14 hours ago














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 13 hours ago









Taras

2,1972726




2,1972726






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 16 hours ago









Mathijs AlkemaMathijs Alkema

112




112




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
    15 hours ago











  • Interesting would be the feature count of both of your layers. It looks like your using OpenStreetMap data. According to big data sets you have to think of spatial indexes.

    – Stefan
    14 hours ago














  • 1





    Which software is that? QGIS or ArcGIS?

    – Taras
    15 hours ago











  • Interesting would be the feature count of both of your layers. It looks like your using OpenStreetMap data. According to big data sets you have to think of spatial indexes.

    – Stefan
    14 hours ago








1




1





Which software is that? QGIS or ArcGIS?

– Taras
15 hours ago





Which software is that? QGIS or ArcGIS?

– Taras
15 hours ago













Interesting would be the feature count of both of your layers. It looks like your using OpenStreetMap data. According to big data sets you have to think of spatial indexes.

– Stefan
14 hours ago





Interesting would be the feature count of both of your layers. It looks like your using OpenStreetMap data. According to big data sets you have to think of spatial indexes.

– Stefan
14 hours ago










2 Answers
2






active

oldest

votes


















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.



from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *

# define input layer points and lines
p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0] # set your point layer name here
l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('lines')[0] # set your line layer name here
lines = [feature for feature in l_lyr.getFeatures()]

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

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

feat =
for points in p_lyr.getFeatures():
# find closest point to line
minDistPoint = min([l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint())) for l in lines])[1]
feat = QgsFeature()
# create line from point to minDistPoint
line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])])
feat.setGeometry(line)
# adding point id, line id and length of the closest distance line as a feature to the memory layer
feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()])
prov.addFeatures([feat])

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


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
    13 hours ago











  • 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
    11 hours ago











  • my shapefiles have an attribute called "id". For the resulting closest distance lines they will be adopted. See the penultimate line in the for loop: feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()]). You have to replace the "id" regarding the attributes of your shapefiles. I can edit the code when only the distance is needed.

    – Stefan
    11 hours ago



















1














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

























    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














    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.



    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from qgis.core import *
    from qgis.gui import *
    from qgis.networkanalysis import *

    # define input layer points and lines
    p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0] # set your point layer name here
    l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('lines')[0] # set your line layer name here
    lines = [feature for feature in l_lyr.getFeatures()]

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

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

    feat =
    for points in p_lyr.getFeatures():
    # find closest point to line
    minDistPoint = min([l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint())) for l in lines])[1]
    feat = QgsFeature()
    # create line from point to minDistPoint
    line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])])
    feat.setGeometry(line)
    # adding point id, line id and length of the closest distance line as a feature to the memory layer
    feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()])
    prov.addFeatures([feat])

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


    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
      13 hours ago











    • 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
      11 hours ago











    • my shapefiles have an attribute called "id". For the resulting closest distance lines they will be adopted. See the penultimate line in the for loop: feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()]). You have to replace the "id" regarding the attributes of your shapefiles. I can edit the code when only the distance is needed.

      – Stefan
      11 hours 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.



    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from qgis.core import *
    from qgis.gui import *
    from qgis.networkanalysis import *

    # define input layer points and lines
    p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0] # set your point layer name here
    l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('lines')[0] # set your line layer name here
    lines = [feature for feature in l_lyr.getFeatures()]

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

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

    feat =
    for points in p_lyr.getFeatures():
    # find closest point to line
    minDistPoint = min([l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint())) for l in lines])[1]
    feat = QgsFeature()
    # create line from point to minDistPoint
    line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])])
    feat.setGeometry(line)
    # adding point id, line id and length of the closest distance line as a feature to the memory layer
    feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()])
    prov.addFeatures([feat])

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


    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
      13 hours ago











    • 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
      11 hours ago











    • my shapefiles have an attribute called "id". For the resulting closest distance lines they will be adopted. See the penultimate line in the for loop: feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()]). You have to replace the "id" regarding the attributes of your shapefiles. I can edit the code when only the distance is needed.

      – Stefan
      11 hours ago














    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.



    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from qgis.core import *
    from qgis.gui import *
    from qgis.networkanalysis import *

    # define input layer points and lines
    p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0] # set your point layer name here
    l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('lines')[0] # set your line layer name here
    lines = [feature for feature in l_lyr.getFeatures()]

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

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

    feat =
    for points in p_lyr.getFeatures():
    # find closest point to line
    minDistPoint = min([l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint())) for l in lines])[1]
    feat = QgsFeature()
    # create line from point to minDistPoint
    line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])])
    feat.setGeometry(line)
    # adding point id, line id and length of the closest distance line as a feature to the memory layer
    feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()])
    prov.addFeatures([feat])

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


    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.



    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from qgis.core import *
    from qgis.gui import *
    from qgis.networkanalysis import *

    # define input layer points and lines
    p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('points')[0] # set your point layer name here
    l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('lines')[0] # set your line layer name here
    lines = [feature for feature in l_lyr.getFeatures()]

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

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

    feat =
    for points in p_lyr.getFeatures():
    # find closest point to line
    minDistPoint = min([l.geometry().closestSegmentWithContext(QgsPoint(points.geometry().asPoint())) for l in lines])[1]
    feat = QgsFeature()
    # create line from point to minDistPoint
    line = QgsGeometry.fromPolyline([QgsPoint(points.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])])
    feat.setGeometry(line)
    # adding point id, line id and length of the closest distance line as a feature to the memory layer
    feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()])
    prov.addFeatures([feat])

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


    enter image description here







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 14 hours ago

























    answered 15 hours ago









    StefanStefan

    2,67912041




    2,67912041













    • 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
      13 hours ago











    • 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
      11 hours ago











    • my shapefiles have an attribute called "id". For the resulting closest distance lines they will be adopted. See the penultimate line in the for loop: feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()]). You have to replace the "id" regarding the attributes of your shapefiles. I can edit the code when only the distance is needed.

      – Stefan
      11 hours ago



















    • 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
      13 hours ago











    • 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
      11 hours ago











    • my shapefiles have an attribute called "id". For the resulting closest distance lines they will be adopted. See the penultimate line in the for loop: feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()]). You have to replace the "id" regarding the attributes of your shapefiles. I can edit the code when only the distance is needed.

      – Stefan
      11 hours ago

















    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
    13 hours ago





    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
    13 hours ago













    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
    11 hours ago





    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
    11 hours ago













    my shapefiles have an attribute called "id". For the resulting closest distance lines they will be adopted. See the penultimate line in the for loop: feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()]). You have to replace the "id" regarding the attributes of your shapefiles. I can edit the code when only the distance is needed.

    – Stefan
    11 hours ago





    my shapefiles have an attribute called "id". For the resulting closest distance lines they will be adopted. See the penultimate line in the for loop: feat.setAttributes([int(points["id"]), int(l["id"]), line.geometry().length()]). You have to replace the "id" regarding the attributes of your shapefiles. I can edit the code when only the distance is needed.

    – Stefan
    11 hours ago













    1














    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














      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












        1








        1







        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 14 hours ago

























        answered 14 hours ago









        PieterBPieterB

        2,5061126




        2,5061126






















            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

            How to label and detect the document text images

            Vallis Paradisi

            Tabula Rosettana