使用说明
谷歌地图MCP服务器
用于谷歌地图平台API的生产就绪模型上下文协议(MCP)服务器。
通过标准化的MCP接口,为您的AI代理提供真实世界的位置智能:方向、地点、地理编码、交通分析和道路网络数据。
特性
- 生产准备就绪:强大的错误处理、指数回退的自动重试、结构化日志记录
- 通用集成:适用于Claude Desktop、Google ADK和任何兼容MCP的客户端
- API全面覆盖:涵盖所有主要谷歌地图API的11个工具
- 类型安全:具有Pydantic验证和mypy合规性的完整类型注释
- 零配置:合理的默认设置,开箱即用
- 经过彻底测试通过单元和集成测试,代码覆盖率超过90%
- Docker支持:已准备好部署容器映像
- 优秀的文档:广泛的示例、API参考和最佳实践
- 现代Python:使用uv包管理器为Python 3.10+构建
支持的API和工具
| API | 工具 | 说明 | 使用案例 |
|---|---|---|---|
| 地点API | search_places |
查找地点附近的兴趣点 | 餐厅推荐、加油站查找器、POI搜索 |
| 地点API | get_place_details |
获取一个地方的详细信息 | 开放时间、网站、电话号码、无障碍信息 |
| API指南 | get_directions |
获取实时交通路线 | 路线规划、预计到达时间计算、备选路线 |
| API指南 | get_traffic_conditions |
分析实时交通拥堵 | 通勤监控、延误估计、车队路线 |
| 地理编码API | geocode_address |
将地址转换为坐标 | 地址验证,位置查找 |
| 地理编码API | reverse_geocode |
将坐标转换为地址 | 位置识别、地址查找 |
| 距离矩阵API | calculate_distance_matrix |
多起点/目的地距离 | 车队路线、交付优化、旅行计划 |
| 道路API | snap_to_roads |
将GPS点捕捉到道路网络 | GPS轨迹清理、路线重建 |
| 道路API | get_speed_limits |
检索限速数据 | 车队安全监控、合规性检查 |
| API高程 | get_route_elevation_gain |
计算海拔增益和轮廓 | 自行车/徒步旅行计划、燃油效率 |
| 复合物 | calculate_route_safety_factors |
评估路线安全风险 | 车队安全、保险评分、驾驶员辅助 |
快速开始
先决条件
安装
使用紫外线(推荐)
uv pip install google-maps-mcp-server
使用pip
pip install google-maps-mcp-server
来源
git clone https://github.com/ettysekhon/google-maps-mcp-server.git
cd google-maps-mcp-server
uv sync
设置Google Maps API密钥
- 访问 谷歌云控制台
- 创建新项目或选择现有项目
- 启用以下API:
- 地点API
- API指南
- 地理编码API
- 距离矩阵API
- 道路API
- 创建凭据(API密钥)
- 限制API密钥(推荐):
- 应用程序限制:HTTP引用者或IP地址
- API限制:仅选择上面列出的API
配置
创建一个 .env 工作目录中的文件:
GOOGLE_MAPS_API_KEY=your_maps_api_key_here
LOG_LEVEL=INFO
MAX_RESULTS=20
或设置环境变量:
export GOOGLE_MAPS_API_KEY="your_maps_api_key_here"
运行服务器
# Using the installed command
google-maps-mcp-server
# Or using Python module
python -m google_maps_mcp_server
# Or using uv
uv run google-maps-mcp-server
部署
看 部署.md 有关完整说明、故障排除和架构详细信息。
本地Docker测试
# Set your API key (or create a .env file)
export GOOGLE_MAPS_API_KEY=your-key
# Build and run
make docker-run
# Verify (in another terminal)
make verify-local
GKE部署
# Set environment
export GOOGLE_CLOUD_PROJECT=your-project-id
export GOOGLE_CLOUD_REGION=europe-west2
# First time: create secret
make deploy-secret
# Deploy (build, push, apply)
make deploy-all
# Check status
make deploy-status
代码更改后重新部署
# Rebuild and push new image
make deploy-build
# Force pod to pull new image
kubectl delete pod -l app=google-maps-mcp-server
# Watch for new pod to be ready
kubectl get pods -l app=google-maps-mcp-server -w
MCP检验员测试
使用官方MCP检查器验证您的部署:
npx @modelcontextprotocol/inspector
- 运输类型: 上海证券交易所
- 网址:
http://<EXTERNAL-IP>/sse(或http://localhost:8080/sse本地) - 应看到列出的11个工具
跑 make help 查看所有可用命令。
使用示例
使用克劳德桌面
添加到您的Claude Desktop配置文件中:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
视窗: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"google-maps": {
"command": "uvx",
"args": ["google-maps-mcp-server"],
"env": {
"GOOGLE_MAPS_API_KEY": "your_api_key_here"
}
}
}
}
或者,如果全局安装:
{
"mcpServers": {
"google-maps": {
"command": "google-maps-mcp-server",
"env": {
"GOOGLE_MAPS_API_KEY": "your_api_key_here"
}
}
}
}
现在你可以问克劳德:
- “找到伦敦斯特兰德附近最好的咖啡店”
- “自然历史博物馆的开放时间是什么时候?”
- “现在从伦敦到曼彻斯特的交通怎么样?”
- “从爱丁堡到格拉斯哥的路线适合夜间驾驶吗?”
- 将地址“伦敦唐宁街10号”转换为坐标
- “坐标51.5074,-0.1278的地址是什么?”
- “查找距离我当前位置51.5074,-0.1278 2公里以内的加油站”
使用谷歌ADK
from google.adk.agents import Agent
from google.adk.tools.mcp_tool import MCPToolset
from mcp.client.stdio import StdioServerParameters
async def create_location_agent():
# Connect to Google Maps MCP server
maps_tools = await MCPToolset.from_server(
connection_params=StdioServerParameters(
command='google-maps-mcp-server',
env={"GOOGLE_MAPS_API_KEY": "your_api_key_here"}
)
)
# Create agent with Maps tools
agent = Agent(
name="location_intelligence_agent",
model="gemini-2.0-flash",
instruction="""You are a location intelligence assistant with access to
Google Maps data. Help users with directions, place searches, and location queries.""",
tools=[maps_tools]
)
return agent
# Use the agent
agent = await create_location_agent()
response = await agent.run("Find Italian restaurants near Hyde Park, London")
print(response)
程序化使用
import asyncio
from google_maps_mcp_server import GoogleMapsMCPServer, Settings
async def main():
# Initialise with custom settings
settings = Settings(
google_maps_api_key="your_api_key_here",
log_level="DEBUG",
max_results=10
)
server = GoogleMapsMCPServer(settings)
# Run the server
await server.run()
if __name__ == "__main__":
asyncio.run(main())
直接工具使用
from google_maps_mcp_server.tools import PlacesTool, DirectionsTool
from google_maps_mcp_server.config import Settings
async def find_nearby_restaurants():
settings = Settings(google_maps_api_key="your_key")
places_tool = PlacesTool(settings)
result = await places_tool.execute({
"location": "51.5118,-0.1175", # The Strand, London
"keyword": "pizza",
"radius": 1000
})
print(f"Found {result['data']['count']} pizza places")
for place in result['data']['places']:
print(f"- {place['name']}: {place['rating']}⭐")
asyncio.run(find_nearby_restaurants())
Docker使用
# Build the image
docker build -t google-maps-mcp .
# Run the container
docker run -it \
-e GOOGLE_MAPS_API_KEY=your_maps_key_here \
google-maps-mcp
# Or use docker-compose
docker-compose up
配置选项
所有配置都可以通过环境变量或 .env 文件:
| 变量 | 类型 | 默认值 | 描述 |
|---|---|---|---|
GOOGLE_MAPS_API_KEY |
字符串 | 必需的 | 谷歌地图平台API密钥(用于地图工具) |
LOG_LEVEL |
字符串 | INFO |
日志记录级别(调试、信息、警告、错误、严重) |
MAX_RESULTS |
整数 | 20 |
返回的最大结果(1-60) |
DEFAULT_RADIUS_METERS |
整数 | 5000 |
默认搜索半径(单位:米) |
MAX_RADIUS_METERS |
整数 | 50000 |
最大允许搜索半径 |
MAX_RETRIES |
整数 | 3 |
失败请求的最大重试次数 |
RETRY_MIN_WAIT |
浮子 | 1.0 |
重试之间的最短等待时间(秒) |
RETRY_MAX_WAIT |
浮子 | 10.0 |
重试之间的最大等待时间(秒) |
工具文档
search_places
查找某个位置附近的位置。
参数:
location(必填):坐标为“lat,lng”或地址字符串keyword(必填):搜索关键字(例如“餐厅”、“加油站”)radius(可选):搜索半径,单位为米(默认值:5000,最大值:50000)type(可选):放置类型过滤器(例如“餐厅”、“gas_station”)
例子:
{
"location": "51.5118,-0.1175",
"keyword": "coffee shop",
"radius": 1000,
"type": "cafe"
}
get_place_details
获取特定地点的详细信息。
参数:
place_id(必填):唯一的地点IDfields(可选):要检索的特定字段(例如,[“姓名”、“电话”、“小时”])
例子:
{
"place_id": "ChIJN1t_tDeuEmsRUsoyG83frY4",
"fields": ["name", "website", "hours"]
}
get_directions
通过实时交通获取路线方向。
参数:
origin(必填):起始位置(地址或坐标)destination(必填):结束位置(地址或坐标)mode(可选):旅行模式-“驾驶”(默认)、“步行”、“骑自行车”、“公交”departure_time(可选):用于流量估计的ISO 8601时间戳alternatives(可选):返回备选路线(默认值:true)avoid(可选):要避免的功能-[“通行费”、“高速公路”、“渡轮”、“室内”]traffic_model(可选):“best_guess”(默认)、“乐观”、“悲观”
例子:
{
"origin": "London, UK",
"destination": "Manchester, UK",
"mode": "driving",
"alternatives": true,
"avoid": ["tolls"]
}
get_traffic_conditions
分析两个地点之间的实时交通状况。
参数:
origin(必填):起始位置destination(必填):结束位置departure_time(可选):ISO 8601时间戳(默认为现在)traffic_model(可选):“best_guess”(默认)、“乐观”、“悲观”
例子:
{
"origin": "London, UK",
"destination": "Oxford, UK",
"traffic_model": "best_guess"
}
geocode_address
将地址转换为坐标。
参数:
address(必填):要进行地理编码的街道地址components(可选):组件筛选器(例如,{“国家”:“GB”})region(可选):地区偏差(ISO 3166-1国家代码)
例子:
{
"address": "10 Downing Street, London, UK"
}
reverse_geocode
将坐标转换为地址。
参数:
lat(必填):纬度(-90至90)lng(必填):经度(-180至180)result_type(可选):按结果类型筛选
例子:
{
"lat": 51.5034,
"lng": -0.1276
}
calculate_distance_matrix
计算多个位置之间的距离和时间。
参数:
origins(必填):原点位置数组destinations(必填):目的地位置数组mode(可选):行驶模式(默认:“行驶”)avoid(可选):要避免的功能units(可选):“公制”(默认)或“英制”
例子:
{
"origins": ["London, UK", "Manchester, UK"],
"destinations": ["Birmingham, UK", "Leeds, UK"],
"mode": "driving"
}
snap_to_roads
将GPS坐标捕捉到最近的道路。
参数:
path(必填):带lat/lng的GPS点阵列(2-100个点)interpolate(可选):填补点之间的空白(默认值:true)
例子:
{
"path": [
{"lat": 51.5034, "lng": -0.1276},
{"lat": 51.5035, "lng": -0.1275}
],
"interpolate": true
}
get_speed_limits
获取路段的限速数据。
参数:
place_ids(必需):snap_to_rods中的地点ID数组
例子:
{
"place_ids": ["ChIJwQ2rKwAEdkgRo7h2RYD1oUM"]
}
calculate_route_safety_factors
根据交通、路况和限速计算路线的安全分数。
参数:
origin(必填):起始位置destination(必填):结束位置departure_time(可选):ISO 8601时间戳(默认为现在)traffic_model(可选):“best_guess”、“乐观”、“悲观”(默认)
例子:
{
"origin": "London, UK",
"destination": "Oxford, UK",
"departure_time": "2023-10-27T23:00:00Z",
"traffic_model": "pessimistic"
}
get_route_elevation_gain
计算高程增益并检索路线的高程剖面。
参数:
origin(必填):起始位置destination(必填):结束位置mode(可选):“驾驶”、“步行”、“骑自行车”(默认)samples(可选):高程采样数(默认值:50,最大值:512)
例子:
{
"origin": "London, UK",
"destination": "Brighton, UK",
"mode": "bicycling",
"samples": 100
}
发展
设置开发环境
# Clone the repository
git clone https://github.com/ettysekhon/google-maps-mcp-server.git
cd google-maps-mcp-server
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install dependencies with dev extras
uv sync --extra dev
# Set up pre-commit hooks
uv run pre-commit install
运行测试
# Run all tests
uv run pytest
# Run with coverage
uv run pytest --cov=src --cov-report=html
# Run only unit tests
uv run pytest -m "not integration"
# Run specific test file
uv run pytest tests/unit/test_places.py
# Run with verbose output
uv run pytest -v
代码质量
# Format code
uv run black src tests
# Lint code
uv run ruff check src tests
# Fix linting issues automatically
uv run ruff check src tests --fix
# Type checking
uv run mypy src
# Run all checks
uv run black src tests && \
uv run ruff check src tests && \
uv run mypy src && \
uv run pytest
建筑与出版
# Build package
uv build
# Publish to PyPI (requires authentication)
uv publish
# Build Docker image
docker build -t google-maps-mcp-server:latest .
贡献
我们欢迎捐款!请看 贡献.md 作为指导方针。
快速贡献指南
- 复刻仓库
- 创建要素分支(
git checkout -b feature/amazing-feature) - 进行更改
- 为您的更改添加测试
- 确保所有测试通过(
uv run pytest) - 提交您的更改(
git commit -m 'Add amazing feature') - 推到分支(
git push origin feature/amazing-feature) - 打开拉取请求
API限制和定价
此MCP服务器使用谷歌地图平台API,这些API有以下注意事项:
- 免费层:每月200美元的信用额度(涵盖约28000个地理编码请求或约40000个方向请求)
- 现收现付:定价因API而异
- 速率限制:默认配额适用;可以通过谷歌云控制台增加
成本优化提示:
- 在适当的时候缓存结果
- 使用
alternatives=false不需要时提供方向 - 限制
max_results用于地点搜索 - 为重复查询实现客户端缓存
看 谷歌地图平台定价 了解详情。
安全最佳实践
-
API密钥安全性:
- 永远不要将API密钥提交到版本控制
- 使用环境变量或秘密管理
- 通过API、HTTP引用或IP地址限制API密钥
- 定期旋转按键
-
API关键限制(推荐):
Application restrictions: HTTP referrers or IP addresses API restrictions: - Places API - Directions API - Geocoding API - Distance Matrix API - Roads API -
监控:
- 在Google Cloud控制台中启用计费警报
- 定期监控API的使用情况
- 设置配额警报
故障排除
常见问题
问题: ValidationError: google_maps_api_key cannot be empty
- 解决方案: 确保
GOOGLE_MAPS_API_KEY环境变量已设置
问题: REQUEST_DENIED 错误
- 解决方案: 在Google云控制台中启用所需的API,并检查API密钥限制
问题: OVER_QUERY_LIMIT 错误
- 解决方案: 您已超过API配额。在Google Cloud Console中检查使用情况或实施速率限制
问题: 服务器无法启动
- 解决方案: 检查日志中的错误,验证Python版本(3.10+),确保安装了所有依赖项
启用调试日志
export LOG_LEVEL=DEBUG
google-maps-mcp-server
获取帮助
许可证
此项目根据Apache许可证2.0获得许可-请参阅 许可证 文件以获取详细信息。