如何使用 Python 获取城市的经纬度?
要获取城市的经纬度,我们将使用 **geopy** 模块。**geopy** 使用第三方地理编码器和其他数据源来查找地址、城市、国家/地区等的坐标。
首先,确保已安装 **geopy** 模块:
pip install geopy
在以下示例中,我们将使用 **Nominatim** 地理编码器查找“海德拉巴”市的经纬度。
步骤:
从 **geopy** 模块导入 **Nominatim 地理编码器**。
初始化 Nominatim API 并使用 **geocode** 方法获取输入字符串的位置。
最后,通过 **location.latitude** 和 **location.longitude** 获取位置的纬度和经度。
示例 1
# Import the required library
from geopy.geocoders import Nominatim
# Initialize Nominatim API
geolocator = Nominatim(user_agent="MyApp")
location = geolocator.geocode("Hyderabad")
print("The latitude of the location is: ", location.latitude)
print("The longitude of the location is: ", location.longitude)输出
它将在控制台上打印以下输出:
The latitude of the location is: 17.360589 The longitude of the location is: 78.4740613
在这个例子中,让我们做与示例 1 相反的操作。我们将首先提供一组坐标,并找到这些坐标代表的城市、州和国家/地区。我们不会在控制台上打印输出,而是创建一个带有四个标签的 tkinter 窗口 来显示输出。
步骤:
初始化 Nominatium API。
使用 **geolocator.reverse()** 函数并提供坐标(纬度和经度)以获取位置数据。
使用 **location.raw['address']** 获取位置的地址,并遍历数据以使用 **address.get()** 查找城市、州和国家/地区。
在 tkinter 窗口内创建标签以显示数据。
示例 2
from tkinter import *
from geopy.geocoders import Nominatim
# Create an instance of tkinter frame
win = Tk()
# Define geometry of the window
win.geometry("700x350")
# Initialize 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()输出
它将生成以下输出:
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP