要获取城市的经纬度,我们将使用geopy模块。geopy使用第三方地理编码器和其他数据源来定位地址、城市、国家等的坐标。
首先,确保安装了geopy模块 -
pip install geopy
在下面的示例中,我们将使用Nominatim地理编码器来查找城市“Hyderabad”的经度和纬度。
从geopy模块导入Nominatim 地理编码器。
初始化 Nominatim API 并使用geocode方法获取输入字符串的位置。
最后通过location.latitude和location.longitude得到位置的经纬度。
#导入需要的库 fromgeopy.geocodersimport Nominatim #初始化 Nominatim API geolocator = Nominatim(user_agent="MyApp") location = geolocator.geocode("Hyderabad") print("该位置的纬度是: ", location.latitude) print("该位置的经度为: ", location.longitude)输出结果
它将在控制台上打印以下输出 -
该位置的纬度是: 17.360589 该位置的经度为: 78.4740613
在这个例子中,让我们做与示例 1 相反的事情。我们将首先提供一组坐标,然后找到这些坐标所代表的城市、州和国家。我们将创建一个带有四个标签的 tkinter 窗口来显示输出,而不是在控制台上打印输出。
初始化 Nominatium API。
使用该函数并提供坐标(纬度和经度)以获取位置数据。geolocator.reverse()
使用location.raw['address']获取位置的地址,并使用 遍历数据以查找城市、州和国家/地区。address.get()
在 tkinter 窗口中创建标签以显示数据。
from tkinter import * fromgeopy.geocodersimport Nominatim # Create an instance of tkinter frame win = Tk() # Define geometry of the window win.geometry("700x350") #初始化 Nominatim API geolocator = Nominatim(user_agent="MyApp") # Latitude & Longitude input coordinates = "17.3850 , 78.4867" location = geolocator.reverse(coordinates) address = location.raw['address'] # Traverse the data city = address.get('city', '') state = address.get('state', '') country = address.get('country', '') # Create a Label widget label1=Label(text="Given Latitude and Longitude: " + coordinates, font=("Calibri", 24, "bold")) label1.pack(pady=20) label2=Label(text="The city is: " + city, font=("Calibri", 24, "bold")) label2.pack(pady=20) label3=Label(text="The state is: " + state, font=("Calibri", 24, "bold")) label3.pack(pady=20) label4=Label(text="The country is: " + country, font=("Calibri", 24, "bold")) label4.pack(pady=20) win.mainloop()输出结果
它将产生以下输出 -