Welcome folks today in this blog post we will be calculating the distance between two states and cities locations using geopy module using python. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below libraries using the geopy
module as shown below
pip install geopy
After installing this module you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from geopy.geocoders import Nominatim from geopy import distance geocoder = Nominatim(user_agent="Coding Shiksha") location1 = "Texas" location2 = "Chicago" coordinates1 = geocoder.geocode(location1) coordinates2 = geocoder.geocode(location2) lat1,long1 = (coordinates1.latitude),(coordinates1.longitude) lat2,long2 = (coordinates2.latitude),(coordinates2.longitude) place1 = (lat1,long1) place2 = (lat2,long2) print(distance.distance(place1,place2)) |
As you can see we are importing the distance
method from the geopy module. And then we are reverse geocoding the locations to latitude and longitude using the geocode()
method. And then we are getting the coordinates. Now to get the latitude and longitude we will be using the dot
syntax. And lastly we will be calculating the distance between two latitude,longitude points using the distance()
method of geopy module.
Now if you run the python
script you will see the below output in km.