How to find the distance between two points in same layer?

I tried the following with no success:

from qgis.core import QGis

lyr = QgsVectorLayer("D:/QGIS/qgis_data/nyc/NYC_MUSEUMS_GEO.shp","Museums", "ogr")
#fts = lyr.getFeatures()
l = QgsProject.instance().mapLayersByName(lyr)
for f in lyr.getFeatures():
    last = f
    d = QgsDistanceArea()
    m = d.measureLine(first.geometry().asPoint(), last.geometry().asPoint())
    deg = QGis.DecimalDegrees
    met = QGis.Meters
    d.convertMeasurement(m, deg, met, False)

and go the following error:

TypeError: 'QgsVectorLayer' object does not support indexing

  • I need to measure the distance btwn two points. I tried manually giving the point 1 and point2 value point1 = QgsPoint(80.69,12.56) point2 = QgsPoint(80.02,14.20) #Create a measure object distance = QgsDistanceArea() distance.setEllipsoid('WGS84') distance = point1.distance(point2) print(distance) This code is working fine.. but i need to measure the distance by the name of the region through pycode . so tried above code which mentioned not success.. Please help me
    – vid
    Jun 16, 2021 at 11:27

1 Answer 1


Try storing your data in a dictionary:

lyr = QgsProject.instance().mapLayersByName('ne_10m_populated_places_simple')[0]

#Create a dictionary of placename and point geometry. Change 'name' to your columnname. (This wont work with duplicates on name though!)
namegeom = {f['name']:f.geometry().asPoint() for f in lyr.getFeatures()}

distance = QgsDistanceArea()

def distanceInMeters(city1, city2):
 """return the distance between two cities"""
    return distance.measureLine(namegeom[city1], namegeom[city2])

print(distanceInMeters('Las Vegas', 'Flagstaff'))

enter image description here

  • 1
    Thanks BERA.. It is working fine
    – vid
    Jun 16, 2021 at 12:57
  • 1
    Nice! Please accept my answer with the checkbox if it solved your question
    – BERA
    Jun 16, 2021 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.