I have two shapefiles

  1. Blue network
  2. yellow locations

as shown in the below figure.

I want to connect all yellow dots with the blue lines blue as shown in red color in the figure.

Is there a way to connect all the yellow circles (buildings) to blues lines(roads)?

enter image description here


1 Answer 1


This is not taking any attributes into account (for example road name stored in each address point), just finds closest road using closestSegmentWithContext. Then you can merge (or spatial join etc.) output lines with your roads.

roadlyr = QgsProject.instance().mapLayersByName('TR_ROAD')[0]
addrlyr = QgsProject.instance().mapLayersByName('ADDRESS')[0]

#List all features
adresses = [f for f in addrlyr.getFeatures()]
roads = [f for f in roadlyr.getFeatures()] 

#Create empty vector layer
vl = QgsVectorLayer("LineString?crs={}&index=yes".format(roadlyr.crs().authid()), "myLayer", "memory")
provider = vl.dataProvider()

#For each adress find closest road
for adress in adresses:
    closest_road = min([road.geometry().closestSegmentWithContext(adress.geometry().asPoint()) for road in roads], key=lambda x: x[0]) #Find which road is closest to current address. Index 0 is the distance
    gLine = QgsGeometry.fromPolyline([QgsPoint(adress.geometry().asPoint()), QgsPoint(closest_road[1])]) #Index 1 is the PointXY geometry of the closest road location
    f = QgsFeature()


enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.