Refactor geocoding function to improve error handling and response messages
Browse files
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 |
-
|
| 15 |
-
|
| 16 |
-
# OpenStreetMap. It doesn't require an API key for basic use.
|
| 17 |
-
# geolocator = Nominatim(user_agent="geocalc_mcp_app")
|
| 18 |
|
| 19 |
-
|
| 20 |
-
# location = geolocator.geocode(address)
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 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."
|
|
|