如何使用 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()

輸出

它將生成以下輸出:

更新於: 2023-08-29

30K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.