Flutter调用Google Maps/Apple Maps导航功能问题求助
解决Flutter调用Google/Apple Maps导航失效问题
一、先排查Google Maps调用失效的核心原因
1. 补全url_launcher的平台配置
Android(API 30+)必须在AndroidManifest.xml中添加应用查询权限,否则无法检测到已安装的Google Maps:
<queries> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="https" /> </intent> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="google.navigation" /> </intent> </queries>
iOS需要在Info.plist中添加允许查询的应用Scheme:
<key>LSApplicationQueriesSchemes</key> <array> <string>comgooglemaps</string> <string>maps</string> </array>
2. 修正Google Maps的URI参数
你第二种写法的参数逻辑错误:google.navigation:q=后应该填目标位置,而非当前位置,正确写法:
await launchUrl( Uri.parse("google.navigation:q=${vendorPosition.latitude},${vendorPosition.longitude}&mode=d"), mode: LaunchMode.externalApplication, // 强制打开外部应用,而非Web视图 );
如果用HTTP链接,要确保参数完整并指定启动模式:
final url = "https://www.google.com/maps/dir/?api=1" "&origin=${position.latitude},${position.longitude}" "&destination=${vendorPosition.latitude},${vendorPosition.longitude}" "&travelmode=driving"; await launchUrlString(url, mode: LaunchMode.externalApplication);
二、添加Apple Maps的跨平台适配
针对iOS设备,单独处理Apple Maps的导航URI:
final appleMapsUrl = "http://maps.apple.com/?saddr=${position.latitude},${position.longitude}" "&daddr=${vendorPosition.latitude},${vendorPosition.longitude}" "&dirflg=d"; // d=驾车,w=步行,r=公交 await launchUrlString(appleMapsUrl, mode: LaunchMode.externalApplication);
三、完整的跨平台实现代码
通过平台判断自动切换地图应用,同时增加可用性校验:
import 'dart:io'; import 'package:url_launcher/url_launcher.dart'; Future<void> startNavigation( double originLat, double originLng, double destLat, double destLng ) async { String targetUrl; if (Platform.isIOS) { targetUrl = "http://maps.apple.com/?saddr=$originLat,$originLng&daddr=$destLat,$destLng&dirflg=d"; } else { targetUrl = "google.navigation:q=$destLat,$destLng&mode=d"; // 备选HTTP链接(当Google Maps未安装时会跳转Web版) // targetUrl = "https://www.google.com/maps/dir/?api=1&origin=$originLat,$originLng&destination=$destLat,$destLng&travelmode=driving"; } if (await canLaunchUrlString(targetUrl)) { await launchUrlString(targetUrl, mode: LaunchMode.externalApplication); } else { // 这里可以添加降级逻辑,比如提示用户安装地图应用 throw "无法打开地图应用"; } }
四、关键注意事项
- 必须先调用
canLaunchUrlString校验URI可用性,避免崩溃 - Android 11+的
<queries>配置和iOS的LSApplicationQueriesSchemes是必填项,否则无法检测已安装应用 - 确保经纬度参数无多余空格或格式错误
内容的提问来源于stack exchange,提问作者Fardeen Khan
相关产品推荐
相关产品推荐

