Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- from geopy.geocoders import Nominatim
- from geopy.distance import geodesic
- def main():
- # Load the schools data from a JSON file
- try:
- with open('schools.json', 'r') as f:
- schools_data = json.load(f)
- except Exception as e:
- print(f"Error reading schools.json: {e}")
- return
- # Get user input for address and search radius in miles
- address = input("Enter your address: ")
- try:
- radius_miles = float(input("Enter search radius (in miles): "))
- except ValueError:
- print("Please enter a valid number for the distance.")
- return
- # Geocode the user-supplied address
- geolocator = Nominatim(user_agent="school_locator_app")
- location = geolocator.geocode(address)
- if location is None:
- print("Could not geocode the provided address. Please try a different address.")
- return
- user_coords = (location.latitude, location.longitude)
- print(f"Your location: {user_coords[0]:.6f}, {user_coords[1]:.6f}")
- # Find all schools within the specified radius
- matching_schools = []
- for school_name, coords in schools_data.items():
- school_coords = (coords['lat'], coords['lon'])
- # Calculate the geodesic distance in miles
- distance = geodesic(user_coords, school_coords).miles
- if distance <= radius_miles:
- matching_schools.append((school_name, distance))
- # Sort the results by distance
- matching_schools.sort(key=lambda x: x[1])
- # Print the results
- if matching_schools:
- print(f"\nSchools within {radius_miles} miles:")
- for school, dist in matching_schools:
- print(f" - {school}: {dist:.2f} miles")
- else:
- print(f"\nNo schools found within {radius_miles} miles.")
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment