6

I tried to calculate distance between QgsPoint objects in qgis, i used QgsPoint StartPoint.sqrDist(EndPoint).

but i don't find an expected result, i also tried

import math
math.sqrt(StartPoint.sqrDist(EndPoint))

but still getting a very high result. does somebody know a way how to calculate distance in meter between 2 Qgspoint objects.

underdark
  • 84,148
  • 21
  • 231
  • 413
fkili mohamed
  • 993
  • 12
  • 27

2 Answers2

7

You need a QgsDistanceArea object:

self.distancearea = QgsDistanceArea()
self.distancearea.setSourceCrs( self.canvas.mapRenderer().destinationCrs().srsid())
ellispoid = QgsProject.instance().readEntry("Measure", "/Ellipsoid", GEO_NONE)
self.distancearea.setEllipsoid(ellispoid[0])
mode = self.canvas.mapRenderer().hasCrsTransformEnabled()
self.distancearea.setEllipsoidalMode(ellispoidemode)

distance = self.distancearea.measureLine( start, end)
Nathan W
  • 34,706
  • 5
  • 97
  • 148
7

It is a simple geometry problem, not a PyQGIS problem.

If the unit of the projection system is meter, according to the Euclidean distance formula, the distance between two points in the plane is given by:

def euclidean_distance(point1,point2):
    return math.sqrt((point2.x()-point1.x())**2 + (point2.y()-point1.y())**2)
pt1 = QgsPoint(50,50)
pt2 = QgsPoint(150,150)
print euclidean_distance(pt1,pt2)
141.42135623730951

Using sqrDist, the square distance between the two points:

def qgisdist(point1,point2):
     return math.sqrt(point1.sqrDist(point2))
print qgisdist(pt1,pt2)
141.42135623730951

So the result is the Euclidean Distance and, if the unit is not meter, you cannot use sqrDist.

You need to use other distances as the Haversine formula (look at QGIS - How to calculate distances in a point sequence?)

The solution of Nathan W is to change the projection with PyQGIS2.

gene
  • 54,868
  • 3
  • 110
  • 187
  • i tried QgsGeometry().fromPoint(EndPoint).distance(QgsGeometry().fromPoint(StPoint)) – fkili mohamed Apr 25 '14 at 20:01
  • It is also the Euclidean Distance: QgsGeometry().fromPoint(pt1t).distance(QgsGeometry().fromPoint(pt2)) = 141.42135623730951 – gene Apr 25 '14 at 20:09