Dùng module geopy với geocoder Nominatim để tìm tọa độ địa lý. Cài đặt: pip install geopy.
Các bước (tìm tọa độ từ tên thành phố)
Import Nominatim từ geopy.geocoders.
Khởi tạo Nominatim API, dùng geocode() với tên địa điểm.
Lấy vĩ độ, kinh độ qua location.latitude, location.longitude.
Ví dụ 1: Tìm tọa độ "Hyderabad"
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="MyApp")
location = geolocator.geocode("Hyderabad")
print("Vĩ độ:", location.latitude)
print("Kinh độ:", location.longitude)
Kết quả
The latitude of the location is: 17.360589 The longitude of the location is: 78.4740613
Ví dụ 2: Tìm địa điểm từ tọa độ (reverse geocoding)
Nhập tọa độ, tìm thành phố, bang, quốc gia, hiển thị trên Tkinter.
from tkinter import *
from geopy.geocoders import Nominatim
win = Tk()
win.geometry("700x350")
geolocator = Nominatim(user_agent="MyApp")
coordinates = "17.3850 , 78.4867"
location = geolocator.reverse(coordinates)
address = location.raw['address']
city = address.get('city', '')
state = address.get('state', '')
country = address.get('country', '')
Label(win, text="Given Latitude and Longitude: " + coordinates, font=("Calibri", 24, "bold")).pack(pady=20)
Label(win, text="The city is: " + city, font=("Calibri", 24, "bold")).pack(pady=20)
Label(win, text="The state is: " + state, font=("Calibri", 24, "bold")).pack(pady=20)
Label(win, text="The country is: " + country, font=("Calibri", 24, "bold")).pack(pady=20)
win.mainloop()
Kết quả
Cửa sổ Tkinter hiển thị thành phố, bang, quốc gia tương ứng tọa độ.
