Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 Script to Calculate Distance Between Two States & Cities Locations Using Geopy Module

Posted on December 13, 2022

 

 

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

 

 

Python
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.

 

 

Recent Posts

  • Android Java Project to Merge Multiple PDF Documents From Gallery Using iTextPDF Library
  • Android Java Project to Detect System Hardware & System CPU Info & Display inside TextView Widget
  • Android Java Project to Integrate Google OAuth2 Login & Logout System & Save User Info in SharedPreferences
  • Android Java Project to Export Raw Text to PDF Document Using iTextPDF Library
  • Android Java Project to Export Images From Gallery to PDF Document Using iTextPDF Library
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme