Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีหาพิกัดละติจูดและลองจิจูดของเมืองด้วย Python (geopy)

เพื่อหาพิกัดละติจูดและลองจิจูดของเมือง เราใช้โมดูล geopy ซึ่งใช้ geocoder ภายนอกและแหล่งข้อมูลอื่นๆ ในการหาพิกัดของที่อยู่ เมือง ประเทศ เป็นต้น

ขั้นแรก ติดตั้งโมดูล geopy:

pip install geopy

ตัวอย่างนี้ใช้ geocoder Nominatim หาพิกัดของเมือง "Hyderabad"

ขั้นตอน

  • นำเข้า Nominatim geocoder จากโมดูล geopy

  • เริ่มต้น Nominatim API และใช้เมธอด geocode หาตำแหน่งจากสตริงอินพุต

  • ดึงละติจูดและลองจิจูดจาก location.latitude และ location.longitude

ตัวอย่างที่ 1: หาพิกัดจากชื่อเมือง

from geopy.geocoders import Nominatim

# เริ่มต้น 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

ตัวอย่างที่ 2: หาชื่อเมืองจากพิกัด (Reverse Geocoding)

ตัวอย่างนี้ทำกันย้อนกลับ: ให้พิกัด แล้วหาชื่อเมือง รัฐ และประเทศ แสดงผลในหน้าต่าง tkinter

ขั้นตอน

  • เริ่มต้น Nominatim API

  • ใช้ geolocator.reverse() ใส่พิกัด (ละติจูดและลองจิจูด) เพื่อได้ข้อมูลตำแหน่ง

  • ดึงที่อยู่จาก location.raw['address'] และค้นหาเมือง รัฐ ประเทศด้วย address.get()

  • สร้าง label ใน tkinter window แสดงข้อมูล

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', '')

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()

ผลลัพธ์

วิธีหาพิกัดละติจูดและลองจิจูดของเมืองด้วย Python (geopy)