Flutter调用Routes API而非Directions API获取高精度折线的请求示例
Flutter 调用 Google Routes API 获取高精度折线示例
准备工作
- 确保已在Google Cloud控制台启用Routes API,并获取有效的API密钥
- 在
pubspec.yaml中添加依赖(http用于发送请求,flutter_polyline_points用于解码折线):
dependencies: flutter: sdk: flutter http: ^1.1.0 flutter_polyline_points: ^1.0.0
完整实现代码
1. 导入依赖
import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:flutter_polyline_points/flutter_polyline_points.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart';
2. 核心请求函数
// 替换为你的Google Routes API密钥 const String apiKey = 'YOUR_GOOGLE_ROUTES_API_KEY'; Future<List<LatLng>?> fetchHighPrecisionRoute() async { final url = Uri.parse('https://routes.googleapis.com/directions/v2:computeRoutes'); // 构建请求体,指定高精度折线参数 final requestBody = jsonEncode({ "origin": { "location": { "latLng": { "latitude": 37.7749, // 起点纬度 "longitude": -122.4194 // 起点经度 } } }, "destination": { "location": { "latLng": { "latitude": 37.3352, // 终点纬度 "longitude": -121.8811 // 终点经度 } } }, "travelMode": "DRIVING", "polylineQuality": "HIGH_QUALITY", // 关键:开启高精度折线 "routeModifiers": { "avoidTolls": false, "avoidHighways": false } }); try { final response = await http.post( url, headers: { 'Content-Type': 'application/json', 'X-Goog-Api-Key': apiKey, // 指定返回字段,减少响应体积并符合API要求 'X-Goog-FieldMask': 'routes.polyline.encodedPolyline' }, body: requestBody, ); if (response.statusCode == 200) { final data = jsonDecode(response.body); final encodedPolyline = data['routes'][0]['polyline']['encodedPolyline']; // 解码高精度折线为坐标点列表 final polylinePoints = PolylinePoints(); final result = polylinePoints.decodePolyline(encodedPolyline); return result.map((point) => LatLng(point.latitude, point.longitude)).toList(); } else { print('请求失败:${response.statusCode} - ${response.body}'); return null; } } catch (e) { print('请求异常:$e'); return null; } }
关键参数说明
polylineQuality: "HIGH_QUALITY":这是获取高精度折线的核心配置,Routes API会返回比Directions API更精细的路径点X-Goog-FieldMask:Routes API强制要求指定返回字段,这里仅请求折线相关内容,提升请求效率origin和destination可根据业务需求替换为动态坐标
使用示例
在Widget的初始化逻辑或交互事件中调用:
@override void initState() { super.initState(); fetchHighPrecisionRoute().then((routePoints) { if (routePoints != null) { // 处理路径坐标,比如在Google Maps上绘制折线 print('获取到${routePoints.length}个高精度路径点'); } }); }
内容的提问来源于stack exchange,提问作者Fayis Fazio
相关产品推荐
相关产品推荐

