How to calculate distance in meter between QgsPoint objects in PyQgis?

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.

-

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.

-
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
i'm fine using Euclidean Distance thanks – fkili mohamed Apr 25 '14 at 20:41

You need a `QgsDistanceArea` object:

``````self.distancearea = QgsDistanceArea()
self.distancearea.setSourceCrs( self.canvas.mapRenderer().destinationCrs().srsid())