Question

I am using OGR Distance in Python to determine the shortest distance between a point and a line. My results are completely different then the ones I get using QGIS. I assume the units OGR uses depend on the coordinate system? Could it be that OGR uses degrees? If so how could I convert these to meters? My code looks like this:

import ogr

driver = ogr.GetDriverByName('ESRI Shapefile')

roads = driver.Open('G:/Basedata/OR/infra/TigerRoads2010/OR_TIGERroads_2010_merge.shp', 0)
point = driver.Open('U:/My Documents/Tool/shp/testareacentro.shp', 0)

roadslayer = roads.GetLayer()
pointl = point.GetLayer()

roadsfeature = roadslayer.GetNextFeature()
pointf = pointl.GetNextFeature()

roadgeom = roadsfeature.GetGeometryRef()
pointgeom = pointf.GetGeometryRef()

dist = pointgeom.Distance(roadgeom)

print dist
Was it helpful?

Solution

The reason why my distance is off, is because I only compared the first feature. This will code will give the same results as in QGIS:

import ogr

driver = ogr.GetDriverByName('ESRI Shapefile')

lineshp = driver.Open('U:/My Documents/Tool/shp/line.shp', 0)
linelyr = lineshp.GetLayer()

pointshp = driver.Open('U:/My Documents/Tool/shp/point.shp', 0)
pointlyr = pointshp.GetLayer()

linefeat = linelyr.GetNextFeature()
pointfeat = pointlyr.GetNextFeature()

point_geom = pointfeat.GetGeometryRef()

distlist = []
while linefeat:
    line_geom = linefeat.GetGeometryRef()
    dist = point_geom.Distance(line_geom)
    distlist.append(dist)
    linefeat.Destroy()
    linefeat = linelyr.GetNextFeature()

print min(distlist)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top