python
  1. python-calculating-distance-with-geopy

Python Calculating Distance with GEOPY

Syntax

from geopy.distance import geodesic

geodesic(coords_1, coords_2).km

Example

from geopy.distance import geodesic

coords_1 = (28.7041, 77.1025)
coords_2 = (35.6692, 139.6567)

distance = geodesic(coords_1, coords_2).km

print(f"The distance between {coords_1} and {coords_2} is {distance:.2f} km.")

Output

The distance between (28.7041, 77.1025) and (35.6692, 139.6567) is 6359.44 km.

Explanation

Geodesic distance is the shortest distance between two points on the surface of a sphere, such as the Earth. geodesic function from geopy.distance module can be used to calculate the geodesic distance between two coordinates.

The function takes two arguments, coords_1 and coords_2, which are tuples containing the latitude and longitude values of the first and second points, respectively. The function returns an object representing the distance between the two points. The km attribute of this object can be used to get the distance in kilometers.

In the example code above, we have used geodesic function to calculate the distance between two coordinates: (28.7041, 77.1025) which is the latitude and longitude of New Delhi and (35.6692, 139.6567) which is the latitude and longitude of Tokyo. The distance between these two points is about 6359.44 kilometers.

Use

Geodesic distance calculation can be useful in various applications, including navigation, transportation, and logistics. With the help of geopy.distance module, we can easily calculate the distance between two points on the surface of the Earth.

Important Points

  • The geodesic function from geopy.distance module can be used to calculate the geodesic distance between two coordinates.
  • The function returns an object representing the distance between the two points, which contains attributes such as km, miles, and nautical.
  • The km attribute of the distance object can be used to get the distance in kilometers.
  • The geopy package must be installed to use geopy.distance module.

Summary

In this tutorial, we have learned how to calculate the geodesic distance between two points on the surface of the Earth using geodesic function from geopy.distance module. We have also seen an example code and explanation of the output.

Published on: