Skip to content
Blog

Geocoding and Map Search Tools with Google Maps Platform

Equip Google ADK agents with spatial intelligence by integrating Google Maps Platform Geocoding, Places API, and Distance Matrix tools.

Published on • November 29, 2026

AI Assistant

Location-aware AI assistants—from delivery routing bots and field service dispatchers to travel planners and real estate concierges—need spatial reasoning capabilities. While language models understand general geographic relationships, they cannot compute real-time driving traffic, verify postal address validity, or fetch accurate venue operating hours without deterministic APIs.

In this tutorial, we will build a production-grade geospatial toolset for Google Agent Development Kit (ADK) using Google Maps Platform APIs (Geocoding, Places API, and Distance Matrix).


1. Why Spatial Intelligence Demands External Tooling

LLMs frequently hallucinate travel durations and road connectivity:

  1. Topological Disconnects: LLMs evaluate “as the crow flies” straight-line distances rather than navigable road networks, bridges, or one-way systems.
  2. Dynamic Operating Data: Restaurant and business opening hours change on holidays; venue status can be temporarily closed.
  3. Address Canonicalization: Ambiguous addresses need latitude/longitude coordinates (LatLng) and Place IDs to avoid routing mistakes.
+-------------------------------------------------------------+
|                      Google ADK Agent                       |
|   Prompt: "Find Italian restaurants near Central Park       |
|            within 15 minutes drive of Times Square"         |
+-------------------------------------------------------------+
                               |
                               v
+-------------------------------------------------------------+
|                     Geospatial Tools                        |
|                                                             |
|   1. geocode_address("Times Square, NY") -> Lat/Lng         |
|   2. search_places_nearby(center, radius, type="restaurant")|
|   3. compute_travel_matrix(origin, destinations, mode="car")|
+-------------------------------------------------------------+
                               |
                               v
+-------------------------------------------------------------+
|                 Google Maps Platform APIs                   |
|       - Geocoding API                                       |
|       - Places API (New)                                    |
|       - Routes / Distance Matrix API                        |
+-------------------------------------------------------------+

2. Setting Up the Google Maps Toolset

First, install the official Google Maps Python client:

pip install googlemaps google-adk

Now, let’s create a typed toolset in maps_tools.py:

import os
from typing import Dict, Any, List, Optional
import googlemaps
from pydantic import BaseModel, Field
from google.adk.agents import Agent

class GeocodeInput(BaseModel):
    address: str = Field(description="The postal address or landmark name to geocode.")

class PlacesNearbyInput(BaseModel):
    latitude: float = Field(description="Latitude of the center search location.")
    longitude: float = Field(description="Longitude of the center search location.")
    query: str = Field(description="Search keywords, e.g., 'Italian restaurant', 'pharmacy'.")
    radius_meters: int = Field(default=2000, ge=100, le=50000, description="Search radius in meters.")

class TravelDurationInput(BaseModel):
    origin: str = Field(description="Starting address or 'lat,lng'.")
    destination: str = Field(description="Ending address or 'lat,lng'.")
    mode: str = Field(default="driving", description="'driving', 'walking', 'bicycling', or 'transit'.")

def get_maps_client() -> googlemaps.Client:
    api_key = os.environ.get("GOOGLE_MAPS_API_KEY")
    if not api_key:
        raise ValueError("Missing GOOGLE_MAPS_API_KEY environment variable.")
    return googlemaps.Client(key=api_key)

def geocode_location(input_data: GeocodeInput) -> Dict[str, Any]:
    """Converts a street address or landmark into latitude/longitude coordinates."""
    gmaps = get_maps_client()
    results = gmaps.geocode(input_data.address)
    if not results:
        return {"status": "not_found", "message": f"No coordinates found for {input_data.address}"}

    top_result = results[0]
    location = top_result["geometry"]["location"]
    return {
        "status": "success",
        "formatted_address": top_result.get("formatted_address"),
        "place_id": top_result.get("place_id"),
        "latitude": location["lat"],
        "longitude": location["lng"],
    }

def find_places_nearby(input_data: PlacesNearbyInput) -> Dict[str, Any]:
    """Discovers nearby places matching a query around specific coordinates."""
    gmaps = get_maps_client()
    location = (input_data.latitude, input_data.longitude)

    places_res = gmaps.places_nearby(
        location=location,
        radius=input_data.radius_meters,
        keyword=input_data.query,
    )

    items = []
    for place in places_res.get("results", [])[:8]:
        items.append({
            "name": place.get("name"),
            "rating": place.get("rating"),
            "user_ratings_total": place.get("user_ratings_total"),
            "vicinity": place.get("vicinity"),
            "place_id": place.get("place_id"),
            "is_open_now": place.get("opening_hours", {}).get("open_now"),
        })

    return {
        "status": "success",
        "results_count": len(items),
        "places": items,
    }

def calculate_travel_duration(input_data: TravelDurationInput) -> Dict[str, Any]:
    """Calculates road distance and travel time taking real-time traffic into account."""
    gmaps = get_maps_client()
    matrix = gmaps.distance_matrix(
        origins=[input_data.origin],
        destinations=[input_data.destination],
        mode=input_data.mode,
        departure_time="now"
    )

    try:
        element = matrix["rows"][0]["elements"][0]
        if element["status"] != "OK":
            return {"status": "error", "message": f"Routing failed: {element['status']}"}

        return {
            "status": "success",
            "distance": element["distance"]["text"],
            "duration": element["duration"]["text"],
            "duration_in_traffic": element.get("duration_in_traffic", {}).get("text"),
        }
    except (KeyError, IndexError) as exc:
        return {"status": "error", "message": f"Unexpected response structure: {str(exc)}"}

3. Integrating Spatial Tools into an ADK Agent

We now connect our tools to an ADK Agent instance:

concierge_agent = Agent(
    name="spatial_concierge",
    model="gemini-3.8-flash",
    instruction="""
    You are an intelligent local concierge and logistics assistant.
    Guidelines:
    1. If a user provides an address or landmark, first geocode it using `geocode_location`.
    2. Use `find_places_nearby` to discover establishments around the coordinates.
    3. Verify transit or driving times using `calculate_travel_duration` before recommending destinations.
    4. Provide clear, structured recommendations with ratings, distance, and estimated travel times.
    """,
    tools=[geocode_location, find_places_nearby, calculate_travel_duration],
)

4. Query Example and Verification

import asyncio
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

async def main():
    session_service = InMemorySessionService()
    runner = Runner(agent=concierge_agent, session_service=session_service)
    session = await session_service.get_or_create("concierge_turn")

    prompt = (
        "I am at Grand Central Terminal, NY. Find top-rated coffee shops within 1 km, "
        "and tell me how long it takes to walk to the best one."
    )
    print(f"User: {prompt}\n")

    async for event in runner.run_async(session=session, message=prompt):
        if event.content:
            for part in event.content.parts:
                if hasattr(part, "text") and part.text:
                    print(part.text, end="")
    print()

if __name__ == "__main__":
    asyncio.run(main())

5. Cost and Latency Guardrails

  1. Filter Returned Payload Fields: Google Maps charges vary significantly based on whether you request Basic, Contact, or Atmosphere fields. Request only the necessary fields (fields=['formatted_address', 'geometry']).
  2. Cache Coordinates: Geocode results for identical locations rarely change. Cache geocoding responses in memory or Redis with a 30-day TTL to minimize API costs.
  3. Session Coordinate Injection: If your web or mobile app already knows the user’s GPS coordinates, inject them straight into session.state["user_location"] to skip unnecessary initial geocode calls.

Takeaway: Combining Google Maps APIs with Google ADK provides your agents with real-world geographic ground truth, enabling accurate navigation, discovery, and logistics planning.

Sources