PostGIS query for selecting features not connected to rest of road network?

You can easily use PostGIS to select roads that don't intersect any other road:

SELECT id, geom FROM roads a
WHERE NOT EXISTS 
     (SELECT 1 FROM roads b 
      WHERE a.id != b.id
      AND   ST_Intersects(a.geom, b.geom))

You can use this QGIS Python script to detect lines that are not connected to anything:

from qgis.utils import iface

layer = iface.mapCanvas().currentLayer() # Selected layer

featureList = list( layer.getFeatures() ) # Gets all features
allFeatures = { feature.id(): feature for feature in featureList }

# Spatial indexing
spatialIdx = QgsSpatialIndex()
map( spatialIdx.insertFeature, featureList )

resList = [] # ids of features not connected to anything

for f in featureList:

    # List of potentially connected features from spatial indexing
    ids = spatialIdx.intersects( f.geometry().boundingBox() )

    hasNeighbor = False

    for id in ids:
        ifeature = allFeatures[id]

        if ifeature.id() == f.id():
            continue

        # Checks if f is really intersecting with ifeature
        if f.geometry().intersects(ifeature.geometry()):
            hasNeighbor = True
            break # Exit current for loop

    if (not hasNeighbor) and (not f.id() in resList):
        resList.append( f.id() )

print resList

Note that this won't work on multipart lines. I don't think it could be made much faster...


You can strip out the easy roads with @dbaston's method first, then use pgRouting to find the more complicated cases, such as when you have a network of roads that is not connected to some other network.

Choose a road segment which is definitively within the main network, then try to find a route from each other segment to that one. If no route exists, delete the segment.