Guest User

Untitled

a guest
Feb 1st, 2025
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. import json
  2. from geopy.geocoders import Nominatim
  3. from geopy.distance import geodesic
  4.  
  5. def main():
  6. # Load the schools data from a JSON file
  7. try:
  8. with open('schools.json', 'r') as f:
  9. schools_data = json.load(f)
  10. except Exception as e:
  11. print(f"Error reading schools.json: {e}")
  12. return
  13.  
  14. # Get user input for address and search radius in miles
  15. address = input("Enter your address: ")
  16. try:
  17. radius_miles = float(input("Enter search radius (in miles): "))
  18. except ValueError:
  19. print("Please enter a valid number for the distance.")
  20. return
  21.  
  22. # Geocode the user-supplied address
  23. geolocator = Nominatim(user_agent="school_locator_app")
  24. location = geolocator.geocode(address)
  25. if location is None:
  26. print("Could not geocode the provided address. Please try a different address.")
  27. return
  28.  
  29. user_coords = (location.latitude, location.longitude)
  30. print(f"Your location: {user_coords[0]:.6f}, {user_coords[1]:.6f}")
  31.  
  32. # Find all schools within the specified radius
  33. matching_schools = []
  34. for school_name, coords in schools_data.items():
  35. school_coords = (coords['lat'], coords['lon'])
  36. # Calculate the geodesic distance in miles
  37. distance = geodesic(user_coords, school_coords).miles
  38. if distance <= radius_miles:
  39. matching_schools.append((school_name, distance))
  40.  
  41. # Sort the results by distance
  42. matching_schools.sort(key=lambda x: x[1])
  43.  
  44. # Print the results
  45. if matching_schools:
  46. print(f"\nSchools within {radius_miles} miles:")
  47. for school, dist in matching_schools:
  48. print(f" - {school}: {dist:.2f} miles")
  49. else:
  50. print(f"\nNo schools found within {radius_miles} miles.")
  51.  
  52. if __name__ == '__main__':
  53. main()
  54.  
Advertisement
Add Comment
Please, Sign In to add comment