# MapLayer (backend AI agent internally named "ZoningLens")

> Author: Lokesh Ram Chand, software engineer in Hyderabad. Portfolio: https://lokeshrc.me

## 1. Quick Overview
- One-line description: A browser-based geospatial visualization tool for San Diego parcel/zoning data, built with React + OpenLayers on GeoJSON/Esri feature layers, backed by a FastAPI service that does address geocoding, parcel/zone spatial lookups against MongoDB, and an LLM-driven chat agent (Ollama + Milvus RAG) that answers property hazard and CA zoning-code questions.
- Project type: Full-stack side project — React/TypeScript SPA + Python FastAPI backend.
- Status: Active development, unreleased/personal deployment (backend running against `backend.deploy.lokeshrc.me`; no production domain for the frontend found in the repo). Current branch: `feat/backend`.
- Date / duration: Init commit 2025-04-13 through latest commit on `feat/backend` 2026-08-12 — roughly 16 months, ongoing, worked on intermittently.
- Individual / team project: Two contributors. `priyatham` (17 commits) did the initial scaffold. The account behind this repo (git identity `lokeshramchand-ctrl`) has 73+ commits and did the large majority of feature work.
- My role: Primary/sole developer for everything past the initial scaffold — the OpenLayers mapping engine, the layer-config system, the San Diego address search/autocomplete, and the entire FastAPI backend (geocoding, spatial queries, MongoDB integration, Milvus vector search, and the Ollama-based chat agent).

## 2. Problem / Motivation
- What problem does this solve? Checking a property's zoning, hazard exposure (fire/airport/coastal), and applicable CA legislative codes normally requires several disconnected GIS portals and manual lookups (e.g. SANDAG's own GIS viewer, county assessor site, separate hazard-zone maps).
- Who has the problem? Analysts, developers, and researchers who want a lightweight way to explore San Diego geospatial data — framed in the README as a general-purpose "load any GeoJSON" tool, but in practice built out specifically around San Diego parcels/zoning/hazard data and a real-estate-style chat assistant (frontend `package.json` name: `ai-real-estate-tool`).
- Why was it built? To combine spatial lookups (parcel boundary, zoning overlay, hazard zones) with a conversational interface, so a user can type an address or ask a natural-language question and get zoning/hazard answers instead of manually cross-referencing map layers.
- What existed before this? Public GIS portals (e.g. SANDAG ArcGIS FeatureServer, which this project queries directly for several layers) that show one layer at a time with no synthesis across layers and no natural-language interface.

## 3. Solution
- What was built: A React/OpenLayers frontend that lets a user search a San Diego address (Nominatim, hard-locked to San Diego via viewbox + address-field re-validation), then renders 14 SANDAG feature layers (parcels, zoning, sewer/water mains, fire hazard zones, coastal zones, airport influence area, historic districts, etc.) around that point, plus a floating AI chat panel. A FastAPI backend backs this with MongoDB spatial queries (`$geoIntersects`) for address→parcel→hazard-zone lookups, a Milvus-based RAG pipeline over a zoning/ADU PDF handbook and CA legislative codes, and an Ollama-driven tool-calling chat agent that routes user questions to the right backend tool.
- How it solves the problem: Instead of separate map layers, the backend chains address → point geometry → parcel geometry → hazard-layer intersection in one call (`analyze_property_hazards`), and the LLM agent decides when to call that vs. the code-search/handbook-search tools based on the user's question.
- Key features:
  - Address search restricted to San Diego, with debounced Nominatim autocomplete and client-side re-validation of city/county fields (`frontend/src/components/LandingPage.tsx:94-146`).
  - 14 configurable OpenLayers vector layers pulled live from SANDAG's ArcGIS FeatureServer, each with independent radius and styling (`frontend/src/components/Methods/Layers.tsx`).
  - Dark/light themed map UI with a toggleable layer sidebar, coordinate/zoom HUD, and a floating AI chat widget (`frontend/src/components/OpenLayerMap.tsx`).
  - FastAPI endpoints for geocoding, parcel lookup, and fire/airport/coastal zone intersection checks against MongoDB (`backend/app.py:283-365`).
  - Milvus vector search over two collections — a PDF zoning/ADU handbook and a CA legislative-codes table — used both as REST endpoints and as MCP/LLM tool-calling functions (`backend/app.py:106-191`).
  - A single `/api/chat` endpoint that gives Ollama (`llama3.1`) three callable tools (hazard analysis, handbook search, CA code search) and a fallback JSON-parser for when the model emits a raw tool-call JSON blob instead of using proper tool-calling (`backend/app.py:367-482`).
  - An MCP server (`FastMCP("SanDiegoSpatialAgent")`) exposing the same handbook/code search tools over SSE, mounted at `/sse` (`backend/app.py:21,163-191,484`).

## 4. My Contributions
- Exactly what I personally implemented: The OpenLayers map view and its theming/UI (`OpenLayerMap.tsx`), the multi-layer SANDAG config system (`Methods/Layers.tsx`), the San-Diego-restricted address search and autocomplete (`LandingPage.tsx`), and the entire backend — FastAPI app structure, MongoDB geospatial queries, Milvus RAG for both the PDF handbook and CA codes, the Ollama tool-calling chat agent, and the MCP tool server.
- Distinguish my work from team members' work: `priyatham` authored the original scaffold — the initial commit, first Dockerfile, first parcel-loading pass, the first search bar, and the Jenkins CI pipeline (`Jenkinsfile`). I rebuilt/replaced most of that surface: the current OpenLayers map, layer system, search/autocomplete, and all backend code (MongoDB, Milvus, Ollama) are mine, built on top of the scaffold.
- Important decisions I made: See Section 9 (MongoDB over the SANDAG API directly for hazard queries, Milvus for RAG, restricting search to a fixed San Diego viewbox instead of a general geocoder).

## 5. Technical Stack
### Languages
- TypeScript (frontend), Python 3.12 (backend)

### Frameworks / Libraries
- Frontend: React 19, Vite 6, React Router 7, OpenLayers (`ol` 10 + `ol-ext`), GSAP (animations), Leaflet/react-leaflet (present in `package.json` but the active map view uses OpenLayers, not Leaflet), lucide-react (icons)
- Backend: FastAPI, Pydantic v2, `mcp` (FastMCP) for MCP tool serving, Motor (async MongoDB driver), PyMilvus, `ollama` Python client, Uvicorn

### Database
- MongoDB (`geodata` database — collections include `Address_Points_shapefile`, `Parcels_shapefile`, `Fire_Hazard_Severity_Zones_SD_shapefile`, `Airport_Safety_Zones_shapefile`, `Coastal_Zones_shapefile`), queried via GeoJSON `$geoIntersects`.
- Milvus (vector DB) — two collections: `Zoning_Lens` (PDF handbook chunks) and `pubinfo_codes` (CA legislative codes), queried via `pymilvus.MilvusClient`.
- (Prior iteration used MySQL/`pymysql` for a CA-codes ingestion pipeline; that code path was added then removed in the same session — see commits `2ae8883`, `3f6d0cd`, `6258890`, `02df365`.)

### Infrastructure / Cloud
- Self-hosted services on a private LAN: MongoDB at `10.10.10.110`, Ollama at `10.10.10.100:11434`, Milvus at `10.10.10.130:19530` (all hardcoded in `backend/app.py`, not read from environment/config).
- Deployed backend reachable at `https://backend.deploy.lokeshrc.me` (referenced from the frontend chat call).

### Tools
- Docker (separate `Dockerfile` for frontend and backend), Jenkins (`frontend/Jenkinsfile`, currently a stub pipeline with placeholder Build/Test stages), ESLint + TypeScript for the frontend.

### APIs / Services
- Nominatim/OpenStreetMap (address search/autocomplete)
- SANDAG ArcGIS FeatureServer (`geo.sandag.org`) — live source for all 14 map layers
- LegiScan API (`frontend/src/components/LegiScanAPI.tsx`) — separate, currently unrouted-from-UI experiment for CA bill search
- Ollama (local LLM inference: `llama3.1` for chat/tool-calling, `gemma4:latest` for the CA-codes RAG endpoint, `nomic-embed-text-v2-moe` for embeddings)

## 6. Architecture
- High-level architecture: React SPA (map + chat UI) → FastAPI backend → MongoDB (structured spatial data) + Milvus (vector search) + Ollama (LLM inference), plus direct browser calls to third-party APIs (Nominatim, SANDAG ArcGIS) that bypass the backend entirely for map-layer rendering.
- Major components: `LandingPage` (search) → `OpenLayerMap` (map + layer toggles + chat) → FastAPI `app.py` (geocode/parcel/zone/chat/codes endpoints + MCP tool server).
- How components communicate: Frontend talks to SANDAG/Nominatim directly over HTTPS for map data; frontend talks to the FastAPI backend over REST (JSON) for chat and (previously) address/parcel/zone lookups used by `test_agent.py`; backend talks to MongoDB (Motor, async), Milvus (PyMilvus, sync client wrapped in async endpoints), and Ollama (async client) over the internal network.
- Data flow: User search → Nominatim returns coordinates → frontend fans out 14 parallel GeoJSON requests to SANDAG, scoped by per-layer radius around that point → layers render on the OpenLayers map. Separately, a chat message → Ollama decides which tool to call → tool hits MongoDB (hazard/parcel data) or Milvus (RAG context) → result is fed back to Ollama for a final natural-language answer.

## 7. Technical Implementation
### Backend
- Single-file FastAPI app (`backend/app.py`) exposing REST endpoints plus an `FastMCP` tool server mounted at `/sse`. CORS is wide open (`allow_origins=["*"]`).
- Address/parcel matching avoids regex, splitting the input string manually into a house number + street name and using MongoDB's `$regex` operator on the street token (`backend/app.py:196-208, 285-299`).

### Frontend
- Route-based SPA (`react-router-dom`): `/` landing/search, `/open` main map view, `/esri` (Esri-tile variant), `/legi` (LegiScan experiment). All inline-styled with theme objects rather than a CSS framework.

### Database
- MongoDB collections are pre-loaded shapefiles converted to GeoJSON (`*_shapefile` naming) — ingestion process for that data is not in this repo.
- Milvus collections (`Zoning_Lens`, `pubinfo_codes`) are populated by an external ingestion pipeline; a discarded MySQL-based ingestion path for CA codes exists only in git history, not in the current code.

### AI / ML
- RAG over two corpora (zoning/ADU PDF handbook, CA legislative codes) using `nomic-embed-text-v2-moe` embeddings + Milvus similarity search, with `llama3.1`/`gemma4` for generation.
- Tool-calling chat agent with a manual fallback: if Ollama emits the tool call as raw JSON in the message content instead of using the `tool_calls` field, the backend regex-free parses it out and re-dispatches (`backend/app.py:436-452`, mirrored in `backend/test_agent.py`).

### Other important implementation details
- `analyze_property_hazards` fans out three MongoDB lookups concurrently with `asyncio.gather` after resolving address → point → parcel geometry (`backend/app.py:225-235`).
- Frontend layer configs generate SANDAG query URLs per-layer with independent buffer radii, from 1m (parcels) to 100,000m (fire/coastal/airport overlays) (`frontend/src/components/Methods/Layers.tsx`).

## 9. Engineering Decisions
### Decision 1 — Where to run spatial queries
- Problem: Hazard/parcel/zoning checks need geometry intersection, not just simple filtering.
- Options considered: Query SANDAG's ArcGIS FeatureServer directly per hazard check (as already done for map-layer rendering), vs. maintain a local MongoDB copy of the shapefiles.
- What I chose: MongoDB with `$geoIntersects` for anything the chat agent/backend needs (address, parcel, hazard zones).
- Why: Lets the backend chain multiple spatial joins (address → parcel → hazard layers) in one process without depending on ArcGIS REST semantics or rate limits for every chat turn.
- Trade-offs: Requires keeping a separate MongoDB copy of the shapefiles in sync with the source data; map-layer rendering and the chat agent now read from two different data sources (SANDAG live API vs. Mongo snapshot) for overlapping data.

### Decision 2 — Restricting address search to San Diego
- Problem: Nominatim is a global geocoder, but the map layers and hazard data only cover San Diego.
- Options considered: Trust Nominatim's `viewbox`/`bounded` params alone, or add a client-side re-check.
- What I chose: Both — a fixed viewbox on every Nominatim request, plus a second client-side filter on the returned `city`/`county` fields before showing a result (`frontend/src/components/LandingPage.tsx:94-99, 133-146`).
- Why: `bounded=1` on Nominatim narrows results but doesn't guarantee they're actually inside San Diego city/county limits at the edges of the box.
- Trade-offs: Slightly stricter than necessary — a legitimate San Diego address whose Nominatim record has a sparse `address` object (missing city/county) gets filtered out.

### Decision 3 — Building a MySQL ingestion path, then removing it
- Problem: Needed a way to ingest CA code entries for the codes RAG collection.
- Options considered: MySQL via `mysql.connector`, then `pymysql`, vs. no relational ingestion step in this repo at all.
- What I chose: Added `pymysql`-based ingestion endpoints (`3f6d0cd`), then removed the whole MySQL integration two commits later (`02df365`).
- Why: Not documented in commit messages; the net effect is that `backend/app.py` has no MySQL code today, and `pymysql` remains an unused entry in `backend/requirements.txt`.
- Trade-offs: Leaves a dependency (`pymysql`) with no corresponding code — worth pruning from `requirements.txt`.

## 10. Challenges
### Challenge 1 — LLM tool-calling reliability
- Problem: `llama3.1` (via Ollama) sometimes returns a tool-call request as plain JSON text in `message.content` instead of populating `message.tool_calls`.
- Investigation: Reproduced and isolated in `backend/test_agent.py` as a standalone script before wiring the same fix into the FastAPI `/api/chat` endpoint.
- Solution: Detect tool-name substrings in the raw content, `json.loads` it, and reconstruct a synthetic `tool_calls` entry before dispatching (`backend/app.py:436-452`).
- Result: Chat agent no longer silently fails (or echoes JSON back to the user) when the model skips proper tool-calling format.

### Challenge 2 — Keeping address search inside San Diego
- Problem: A generic Nominatim search returns nationwide results, but every downstream layer/hazard lookup assumes a San Diego coordinate.
- Investigation: Tracked across several commits (`da718e5` "restrict search only to California", `b60cd6a` "add validation to only san diego address only", `3f8135b` "implement address autocomplete feature with Nominatim for San Diego") — the constraint was tightened progressively from state-level to city/county-level.
- Solution: Combined server-side `viewbox`/`bounded` params with a client-side address-field check (`isSanDiegoAddress`), applied identically to both the debounced autocomplete and the manual form submit path.
- Result: Out-of-area addresses are rejected before ever reaching the map/layer-loading logic, with an explicit "San Diego address only" error message.

## 13. Security
- Authentication: None on any FastAPI endpoint — all routes are open.
- Authorization: None.
- Input validation: Pydantic models validate request shapes; address parsing is manual string-splitting rather than a validated grammar (`backend/app.py:196-208`).
- Secrets management: **Not implemented** — MongoDB connection string with a plaintext username/password (`backend/app.py:24`), and the LegiScan API key are both hardcoded directly in source and committed to git (`frontend/src/components/LegiScanAPI.tsx:12,27`). CORS also allows all origins. These should be rotated and moved to environment variables/secrets before any public deployment.
- Rate limiting: None server-side; the frontend self-limits Nominatim calls to one request per ~450ms via debounce to stay under Nominatim's usage policy (`frontend/src/components/LandingPage.tsx:160`).

## 14. Deployment
- Hosting: Backend reachable at `https://backend.deploy.lokeshrc.me`; supporting services (MongoDB, Ollama, Milvus) run on a private LAN (`10.10.10.x`), not cloud-hosted.
- CI/CD: `frontend/Jenkinsfile` exists but its Build/Test stages are placeholder `echo` statements — no real pipeline logic yet.
- Docker: Separate `Dockerfile` per side. Backend: `python:3.12-slim`, installs `requirements.txt`, runs Uvicorn on port 8000. Frontend: plain `node` image running `npm run dev` on port 5173 (dev server, not a production Nginx build, despite the README describing an Nginx-based static build).
- Environment configuration: None — all connection strings/hosts/model names/API keys are hardcoded constants in source rather than environment variables.

## 16. What I Learned
- Technical lessons: Tool-calling output from local LLMs (via Ollama) is not always well-formed; production code needs a fallback parser rather than trusting `tool_calls` alone.
- Mistakes: Hardcoded credentials (MongoDB URI, LegiScan API key) and internal IPs committed directly to source control; a MySQL integration was added and then fully reverted within a few commits, suggesting the ingestion approach wasn't settled before implementation started.
- Things I'd do differently: Move all connection strings/API keys/model names into environment variables from the start; decide on one data backend for spatial queries (MongoDB vs. live SANDAG API) instead of using both for overlapping data.

## 17. Future Improvements
- Known limitations: No auth on any backend endpoint; secrets committed to git history; `frontend/Jenkinsfile` doesn't actually build or test anything; README describes a Docker Compose setup and `.gitattributes` file that don't exist in the repo; `pymysql` remains in `backend/requirements.txt` with no corresponding code.
- Technical debt: `LegiScanAPI.tsx` and `OpenLayerEsri.tsx` routes exist in `App.tsx` but aren't linked from the main navigation flow (dead/experimental routes).

## 18. Evidence & Links
- GitHub: `git@github.com:lokeshramchand-ctrl/MapLayer.git`
- Relevant commits: `3f8135b` (San Diego autocomplete), `da718e5`/`b60cd6a` (San Diego/California search restriction), `58131ef`/`3f6d0cd`/`2ae8883`/`6258890`/`02df365` (MySQL integration added then removed), `26b5edb` (property hazard analysis tool + test script), `bc5305b` (Ollama tool-calling agent hardening), `a86cae0` (FastAPI title → "ZoningLens").

## 21. Facts / Claims
- Claim: Built a spatial chat agent that chains address geocoding → parcel lookup → concurrent hazard-zone checks (fire, airport, coastal) into a single tool call.
  Evidence: `backend/app.py:194-235` (`analyze_property_hazards`), exercised end-to-end in `backend/test_agent.py`.

- Claim: Implemented retrieval-augmented generation over two separate corpora (a zoning/ADU PDF handbook and CA legislative codes) using Milvus vector search.
  Evidence: `backend/app.py:106-158` (`search_pdf_handbook`, `search_ca_codes`), REST endpoints at `backend/app.py:240-253`.

- Claim: Added a fallback parser so the chat agent still works when the local LLM returns a malformed/raw-JSON tool call instead of a proper tool-calling response.
  Evidence: `backend/app.py:436-452`; prototyped first in `backend/test_agent.py`.

- Claim: Restricted address search/autocomplete to San Diego using both a Nominatim viewbox and a client-side re-validation of returned address fields.
  Evidence: `frontend/src/components/LandingPage.tsx:11-12, 94-146`; commit history `3f8135b`, `da718e5`, `b60cd6a`.

- Claim: Renders 14 independently configured live GeoJSON layers (parcels, zoning, utilities, hazard zones, historic districts, etc.) sourced from SANDAG's public ArcGIS FeatureServer.
  Evidence: `frontend/src/components/Methods/Layers.tsx`.

## 22. Keywords
- React, TypeScript, OpenLayers, GeoJSON, GIS
- FastAPI, Python, MongoDB, geospatial queries (`$geoIntersects`)
- Milvus, vector search, RAG, embeddings
- Ollama, LLM tool-calling, MCP (Model Context Protocol)
- Nominatim/OpenStreetMap geocoding
- Docker, Jenkins CI
