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


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

  • Sorry if I was to quick, but I deleted the pyqgis tag, because no efforts with code were demonstrated. Moreover, the questioner said that he/she is new to GIS, so I decided that it has to flow gradually. – Taras Jun 23 '20 at 11:56

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.