如何在Flutter、React Native等移动端技术中调用Google Maps实现导航功能
跨端唤起Google Maps应用解决方案
Flutter 实现方案
通用实现逻辑
- 核心是调用平台的URL Schema跳转能力,Google Maps的通用跳转格式为
geo:latitude,longitude?q=查询内容(Android)、comgooglemaps://?q=查询内容(iOS),也可以用统一的https://www.google.com/maps/search/?api=1&query=纬度,经度链接,系统会自动唤起已安装的Google Maps应用。
依赖安装
- 推荐使用官方维护的
url_launcher库处理跳转,先在pubspec.yaml中添加依赖:
dependencies: url_launcher: ^6.2.0
平台配置
- Android:在
android/app/src/main/AndroidManifest.xml的<queries>节点下添加如下配置,适配Android 11+的可见性规则:
<queries> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="geo"/> </intent> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="https" android:host="www.google.com/maps" /> </intent> </queries>
- iOS:在
ios/Runner/Info.plist的<dict>节点下添加Google Maps的Schema白名单:
<key>LSApplicationQueriesSchemes</key> <array> <string>comgooglemaps</string> </array>
核心调用代码
import 'package:url_launcher/url_launcher.dart'; import 'package:flutter/material.dart'; Future<void> launchGoogleMaps(double lat, double lng, String address) async { final Uri androidUrl = Uri.parse('geo:$lat,$lng?q=${Uri.encodeComponent(address)}'); final Uri iosUrl = Uri.parse('comgooglemaps://?q=${Uri.encodeComponent(address)}¢er=$lat,$lng'); final Uri webUrl = Uri.parse('https://www.google.com/maps/search/?api=1&query=$lat,$lng'); bool launched = false; if (Theme.of(BuildContext).platform == TargetPlatform.android) { launched = await launchUrl(androidUrl); } else if (Theme.of(BuildContext).platform == TargetPlatform.iOS) { launched = await launchUrl(iosUrl); } // 本地应用唤起失败时跳转网页版Google Maps if (!launched) { await launchUrl(webUrl); } }
React Native 实现方案
通用实现逻辑
- 直接使用框架自带的
LinkingAPI即可实现跳转能力,如需检测应用是否已安装可搭配react-native-app-installed-check库使用。
平台配置
- Android:同Flutter的Android配置,在
AndroidManifest.xml添加<queries>节点的geo和https相关规则。 - iOS:同Flutter的iOS配置,在
Info.plist的LSApplicationQueriesSchemes数组中添加comgooglemaps。
核心调用代码
import { Linking, Platform } from 'react-native'; const launchGoogleMaps = async (lat, lng, address) => { const androidUrl = `geo:${lat},${lng}?q=${encodeURIComponent(address)}`; const iosUrl = `comgooglemaps://?q=${encodeURIComponent(address)}¢er=${lat},${lng}`; const webUrl = `https://www.google.com/maps/search/?api=1&query=${lat},${lng}`; const targetUrl = Platform.OS === 'ios' ? iosUrl : androidUrl; const canOpen = await Linking.canOpenURL(targetUrl); if (canOpen) { await Linking.openURL(targetUrl); } else { await Linking.openURL(webUrl); } };
通用注意事项
- 所有查询参数都需要做URL编码,避免特殊字符导致跳转失败。
- 若需要实现导航路线跳转,可修改URL参数:
https://www.google.com/maps/dir/?api=1&origin=起点纬度,起点经度&destination=终点纬度,终点经度&travelmode=driving,travelmode支持driving(驾车)、walking(步行)、transit(公共交通)、bicycling(骑行)四类模式。 - 需提前申请用户的位置权限,才能正确传递当前位置作为导航起点。
内容的提问来源于stack exchange,提问作者Louis
相关产品推荐
相关产品推荐

