mashrur950 commited on
Commit
6e19333
·
1 Parent(s): 0d6d4a3

Update geocoding service to use Google Maps API and enhance permissions in settings

Browse files
.claude/settings.local.json CHANGED
@@ -4,7 +4,13 @@
4
  "WebSearch",
5
  "Bash(python app.py:*)",
6
  "WebFetch(domain:github.com)",
7
- "Bash(pip show:*)"
 
 
 
 
 
 
8
  ],
9
  "deny": [],
10
  "ask": []
 
4
  "WebSearch",
5
  "Bash(python app.py:*)",
6
  "WebFetch(domain:github.com)",
7
+ "Bash(pip show:*)",
8
+ "Bash(python test_google_geocoding.py:*)",
9
+ "Bash(pip install:*)",
10
+ "Bash(find:*)",
11
+ "Bash(netstat:*)",
12
+ "Bash(findstr:*)",
13
+ "Bash(taskkill:*)"
14
  ],
15
  "deny": [],
16
  "ask": []
.env.example CHANGED
@@ -5,8 +5,9 @@ AI_PROVIDER=anthropic
5
  ANTHROPIC_API_KEY=your_anthropic_api_key_here
6
  GOOGLE_API_KEY=your_google_api_key_here
7
 
8
- # HERE Maps API Key (for geocoding)
9
- HERE_API_KEY=your_here_api_key_here
 
10
 
11
  # PostgreSQL Database Configuration
12
  DB_HOST=localhost
 
5
  ANTHROPIC_API_KEY=your_anthropic_api_key_here
6
  GOOGLE_API_KEY=your_google_api_key_here
7
 
8
+ # Google Maps API Key (for geocoding)
9
+ # Note: This can be the same as GOOGLE_API_KEY if Maps API is enabled
10
+ GOOGLE_MAPS_API_KEY=your_google_maps_api_key_here
11
 
12
  # PostgreSQL Database Configuration
13
  DB_HOST=localhost
chat/geocoding.py CHANGED
@@ -1,10 +1,10 @@
1
  """
2
  Geocoding service for FleetMind
3
- Handles address validation with HERE API and smart mock fallback
4
  """
5
 
6
  import os
7
- import requests
8
  import logging
9
  from typing import Dict, Optional
10
 
@@ -36,16 +36,23 @@ CITY_COORDINATES = {
36
 
37
 
38
  class GeocodingService:
39
- """Handle address geocoding with HERE API and smart mock fallback"""
40
 
41
  def __init__(self):
42
- self.here_api_key = os.getenv("HERE_API_KEY", "")
43
- self.use_mock = not self.here_api_key or self.here_api_key.startswith("your_")
44
 
45
  if self.use_mock:
46
- logger.info("Geocoding: Using mock (HERE_API_KEY not configured)")
 
47
  else:
48
- logger.info("Geocoding: Using HERE Maps API")
 
 
 
 
 
 
49
 
50
  def geocode(self, address: str) -> Dict:
51
  """
@@ -61,40 +68,36 @@ class GeocodingService:
61
  return self._geocode_mock(address)
62
  else:
63
  try:
64
- return self._geocode_here(address)
65
  except Exception as e:
66
- logger.error(f"HERE API failed: {e}, falling back to mock")
67
  return self._geocode_mock(address)
68
 
69
- def _geocode_here(self, address: str) -> Dict:
70
- """Real HERE API geocoding"""
71
- url = "https://geocode.search.hereapi.com/v1/geocode"
72
-
73
- params = {
74
- "q": address,
75
- "apiKey": self.here_api_key
76
- }
77
-
78
- response = requests.get(url, params=params, timeout=10)
79
- response.raise_for_status()
80
 
81
- data = response.json()
 
 
 
82
 
83
- if not data.get("items"):
84
- # No results found, fall back to mock
85
- logger.warning(f"HERE API found no results for: {address}")
86
- return self._geocode_mock(address)
87
 
88
- # Get first result
89
- item = data["items"][0]
90
- position = item["position"]
 
 
 
91
 
92
- return {
93
- "lat": position["lat"],
94
- "lng": position["lng"],
95
- "formatted_address": item.get("address", {}).get("label", address),
96
- "confidence": "high (HERE API)"
97
- }
98
 
99
  def _geocode_mock(self, address: str) -> Dict:
100
  """
@@ -126,6 +129,6 @@ class GeocodingService:
126
  def get_status(self) -> str:
127
  """Get geocoding service status"""
128
  if self.use_mock:
129
- return "⚠️ Using mock geocoding (add HERE_API_KEY for real)"
130
  else:
131
- return "✅ HERE Maps API connected"
 
1
  """
2
  Geocoding service for FleetMind
3
+ Handles address validation with Google Maps API and smart mock fallback
4
  """
5
 
6
  import os
7
+ import googlemaps
8
  import logging
9
  from typing import Dict, Optional
10
 
 
36
 
37
 
38
  class GeocodingService:
39
+ """Handle address geocoding with Google Maps API and smart mock fallback"""
40
 
41
  def __init__(self):
42
+ self.google_maps_key = os.getenv("GOOGLE_MAPS_API_KEY", "")
43
+ self.use_mock = not self.google_maps_key or self.google_maps_key.startswith("your_")
44
 
45
  if self.use_mock:
46
+ logger.info("Geocoding: Using mock (GOOGLE_MAPS_API_KEY not configured)")
47
+ self.gmaps_client = None
48
  else:
49
+ try:
50
+ self.gmaps_client = googlemaps.Client(key=self.google_maps_key)
51
+ logger.info("Geocoding: Using Google Maps API")
52
+ except Exception as e:
53
+ logger.error(f"Failed to initialize Google Maps client: {e}")
54
+ self.use_mock = True
55
+ self.gmaps_client = None
56
 
57
  def geocode(self, address: str) -> Dict:
58
  """
 
68
  return self._geocode_mock(address)
69
  else:
70
  try:
71
+ return self._geocode_google(address)
72
  except Exception as e:
73
+ logger.error(f"Google Maps API failed: {e}, falling back to mock")
74
  return self._geocode_mock(address)
75
 
76
+ def _geocode_google(self, address: str) -> Dict:
77
+ """Real Google Maps API geocoding"""
78
+ try:
79
+ # Call Google Maps Geocoding API
80
+ result = self.gmaps_client.geocode(address)
 
 
 
 
 
 
81
 
82
+ if not result:
83
+ # No results found, fall back to mock
84
+ logger.warning(f"Google Maps API found no results for: {address}")
85
+ return self._geocode_mock(address)
86
 
87
+ # Get first result
88
+ first_result = result[0]
89
+ location = first_result['geometry']['location']
 
90
 
91
+ return {
92
+ "lat": location['lat'],
93
+ "lng": location['lng'],
94
+ "formatted_address": first_result.get('formatted_address', address),
95
+ "confidence": "high (Google Maps API)"
96
+ }
97
 
98
+ except Exception as e:
99
+ logger.error(f"Google Maps geocoding error: {e}")
100
+ raise
 
 
 
101
 
102
  def _geocode_mock(self, address: str) -> Dict:
103
  """
 
129
  def get_status(self) -> str:
130
  """Get geocoding service status"""
131
  if self.use_mock:
132
+ return "⚠️ Using mock geocoding (add GOOGLE_MAPS_API_KEY for real)"
133
  else:
134
+ return "✅ Google Maps API connected"
requirements.txt CHANGED
@@ -15,6 +15,7 @@ psycopg2-binary>=2.9.9
15
  # API Clients
16
  requests>=2.31.0
17
  httpx>=0.27.1
 
18
 
19
  # Utilities
20
  python-dotenv>=1.0.0
 
15
  # API Clients
16
  requests>=2.31.0
17
  httpx>=0.27.1
18
+ googlemaps>=4.10.0
19
 
20
  # Utilities
21
  python-dotenv>=1.0.0