判断经纬度坐标是否位于美国某州内

6 投票
4 回答
7566 浏览
提问于 2025-04-18 15:08

在Python中,有没有什么函数、库或者其他方法可以检查某个经纬度坐标是否在一个定义好的地理边界内,比如美国的某个州?

举个例子:

坐标32.781065, -96.797117是在德克萨斯州内吗?

4 个回答

0

我只是想在mathisonian的回答基础上再补充一下。

import reverse_geocoder

#create a list of US states (and the District of Columbia)
state_names = ["Alaska", "Alabama", "Arkansas", "Arizona", "California", "Colorado", "Connecticut", "District of Columbia","Delaware", "Florida","Georgia", "Hawaii", "Iowa", "Idaho", "Illinois", "Indiana", "Kansas", "Kentucky", "Louisiana", "Massachusetts", "Maryland", "Maine", "Michigan", "Minnesota", "Missouri", "Mississippi", "Montana", "North Carolina", "North Dakota", "Nebraska", "New Hampshire", "New Jersey", "New Mexico", "Nevada", "New York", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina","South Dakota", "Tennessee", "Texas", "Utah", "Virginia", "Vermont", "Washington", "Wisconsin", "West Virginia", "Wyoming"]

#get the metadata for the latitude and longitude coordinates
results = reverse_geocoder.search((32.781065, -96.797117))

#check if the location is a US state (the 'admin1' variable is where US states are listed)
if results[0]['admin1'] in state_names:
  print(results[0]['admin1'])

这样做应该会输出“Texas”。

1

我会使用requests库来向谷歌地理编码API发送请求。

2

你可以使用 geocoder库,这个库可以通过命令 pip install geocoder 来安装。

import geocoder

results = geocoder.google('32.781065, -96.797117', reverse = True)

print(results.current_result.state_long)

enter image description here

5

你可以使用这个反向地理编码的库,然后检查“admin1”区域是否是某个特定的美国州。

它可以把经纬度坐标转换成像这样的字典:

{
  'name': 'Mountain View', 
  'cc': 'US', 
  'lat': '37.38605',
  'lon': '-122.08385', 
  'admin1': 'California', 
  'admin2': 'Santa Clara County'
}

撰写回答