How to generate lat and long coordinates of city without using APIS in Python.
Easy codes to understand
if anyone would like to plot map graphs using geographical coordinates (The latitude and longitude which define the position of a point on the surface of the Earth .A common choice of coordinates is latitude, longitude.
Latitude lines run east-west and are parallel to each other. If you go north, latitude values increase. Finally, latitude values (Y-values) range between -90 and +90 degrees
But longitude lines run north-south. They converge at the poles. And its X-coordinates are between -180 and +180 degrees.
Cartographers write spherical coordinates (latitudes and longitudes) in degrees-minutes-seconds (DMS) and decimal degrees. For degrees-minutes-seconds, minutes range from 0 to 60. For example, the geographic coordinate expressed in degrees-minutes-seconds for New York City is:
- Latitude: 40 degrees, 42 minutes, 51 seconds N
- Longitude: 74 degrees, 0 minutes, 21 seconds W
We can also express geographic coordinates in decimal degrees. It’s just another way to represent that same location in a different format. For example, here is New York City in decimal degrees:
- Latitude: 40.714
- Longitude: -74.006
Read more here if you like to understand more deeper.
Let’s get started
I am using Jupyter notebook to run the script in this Article.
First, we will be installing Libraries like Nominatim and geopy using PIP.
pip install geopy
pip install Nominatim
now the code is really easy we just need to run this
Case 1: Where only City name is mention
from geopy.geocoders import Nominatimaddress='Nagpur'
geolocator = Nominatim(user_agent="Your_Name")
location = geolocator.geocode(address)
print(location.address)
print((location.latitude, location.longitude))
after running above code this is the output we will get.
Nagpur, Nagpur District, Maharashtra, 440001, India
(21.1498134, 79.0820556)
Case 2: Where both Country and City name is mentioned.
We can run another code as well if we have Country name and city name .
from geopy.geocoders import Nominatim
geolocator = Nominatim()city ="Agra"
country ="India"
loc = geolocator.geocode(city+','+ country)
print("latitude is :-" ,loc.latitude,"\nlongtitude is:-" ,loc.longitude)
output is :
latitude is :- 27.1752554
longtitude is:- 78.0098161
Conclusion
we can generate lat and long using googlemaps APIs as well, but for APIs you have to pay some charges.
I hope this article will help you and save a good amount of time. Let me know if you have any suggestions.
HAPPY CODING.
Sources :