Renzo commited on
Commit
d2b6971
·
1 Parent(s): 74c8d32

Refactor geocoding function to improve error handling and response messages

Browse files
Files changed (1) hide show
  1. tools.py +13 -14
tools.py CHANGED
@@ -11,20 +11,19 @@ def get_coords_from_address(address: str) -> str:
11
  str: A formatted string with the coordinates "Lat: XX.XXXX, Lon: YY.YYYY"
12
  or an error message if the address is not found.
13
  """
14
- print("get_coords_from_address() called with address:", address)
15
- # 1. Initialize a geocoder. Nominatim is a great free option based on
16
- # OpenStreetMap. It doesn't require an API key for basic use.
17
- # geolocator = Nominatim(user_agent="geocalc_mcp_app")
18
 
19
- # 2. Use the geocoder to find the location from the 'address' string.
20
- # location = geolocator.geocode(address)
21
 
22
- # 3. Check if a location was found.
23
- # - If 'location' is not None, extract 'location.latitude' and 'location.longitude'.
24
- # - Format the result into a string like "Lat: 48.8584, Lon: 2.2945".
25
- # - If 'location' is None, return a clear message like "Address not found."
 
 
 
26
 
27
- # For now, you can use a temporary return value to test the interface.
28
- # For example:
29
- # return f"Processing address: {address}"
30
- return "Lat: 48.8584, Lon: 2.2945"
 
11
  str: A formatted string with the coordinates "Lat: XX.XXXX, Lon: YY.YYYY"
12
  or an error message if the address is not found.
13
  """
14
+ try:
15
+ geolocator = Nominatim(user_agent="geocalc_mcp_app_hackathon")
 
 
16
 
17
+ location = geolocator.geocode(address)
 
18
 
19
+ if location:
20
+ # If a location is found, format the latitude and longitude into a string.
21
+ lat = round(location.latitude, 4)
22
+ lon = round(location.longitude, 4)
23
+ return f"Lat: {lat}, Lon: {lon}"
24
+ else:
25
+ return "Address not found. Please try being more specific. E.g., '1600 Amphitheatre Parkway, Mountain View, CA'"
26
 
27
+ except Exception as e:
28
+ print(f"An error occurred: {e}")
29
+ return "An error occurred while trying to contact the geocoding service."