6

Using Python, is there a function, library, or other way to check to see if a certain lat/lon coordinate pair fall within a defined geographical boundary such as a US state?

Example:

Does 32.781065, -96.797117 fall within Texas?

3
  • 1
    I found some links with the google search "python reverse geocoding".
    – Robᵩ
    Jul 29, 2014 at 4:25
  • Regarding the vote to close, I think that OP didn't particularly expect or require that a "tool, [third party] library or off-site resource" would be needed to solve the problem. But it is. Jul 29, 2014 at 4:27
  • 1
    I'm confused. Was there a vote to close this question? If so, why? I asked an honest question that I'm sure would be useful to others. Jul 29, 2014 at 5:56

4 Answers 4

5

You could use the reverse geocode library, and then check that the "admin1" area is a specific US state.

It converts lat/lon coordinates into dictionaries like:

{
  'name': 'Mountain View', 
  'cc': 'US', 
  'lat': '37.38605',
  'lon': '-122.08385', 
  'admin1': 'California', 
  'admin2': 'Santa Clara County'
}
1
  • Excellent find!
    – Lucas925
    Dec 17, 2019 at 1:23
2

You can use the geocoder library which you can install using pip install geocoder.

import geocoder

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

print(results.current_result.state_long)

enter image description here

1

I would use the requests library to send a request to the Google geocoding API.

0

Just to build on mathisonian's answer.

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

That should print "Texas".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.