如何在Flutter中实现点击门店唤起Google Maps导航至目标地点
唤起Google Maps导航的实现方案
根据你的需求,以下分平台给出具体实现步骤:
Android 端
- 获取定位权限:在
AndroidManifest.xml中添加定位权限声明,并在运行时请求ACCESS_FINE_LOCATION权限,用于获取当前位置的经纬度。 - 构造导航Intent:使用Google Maps的专属Intent格式,指定起点(当前位置)和目的地(门店1):
// 假设已通过定位API获取到当前位置的lat、lng,以及门店1的targetLat、targetLng val gmmIntentUri = Uri.parse("google.navigation:q=$targetLat,$targetLng&saddr=$lat,$lng") val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri) // 指定仅唤起Google Maps应用 mapIntent.setPackage("com.google.android.apps.maps") // 检查设备是否安装了Google Maps,避免崩溃 if (mapIntent.resolveActivity(packageManager) != null) { startActivity(mapIntent) }
iOS 端
- 配置定位权限:在
Info.plist中添加NSLocationWhenInUseUsageDescription字段说明定位用途,并在代码中请求定位权限,获取当前位置的经纬度。 - 配置URL Scheme白名单:在
Info.plist的LSApplicationQueriesSchemes数组中添加comgooglemaps,允许应用唤起Google Maps。 - 构造导航链接并唤起:
// 假设已获取当前位置currentLocation,门店1的目标位置targetLocation if let mapsUrl = URL(string: "comgooglemaps://?saddr=\(currentLocation.coordinate.latitude),\(currentLocation.coordinate.longitude)&daddr=\(targetLocation.coordinate.latitude),\(targetLocation.coordinate.longitude)&directionsmode=driving") { if UIApplication.shared.canOpenURL(mapsUrl) { UIApplication.shared.open(mapsUrl, options: [:], completionHandler: nil) } else { // 未安装Google Maps时,唤起网页版导航 if let webUrl = URL(string: "https://www.google.com/maps/dir/?api=1&origin=\(currentLocation.coordinate.latitude),\(currentLocation.coordinate.longitude)&destination=\(targetLocation.coordinate.latitude),\(targetLocation.coordinate.longitude)&travelmode=driving") { UIApplication.shared.open(webUrl) } } }
Web 端
直接构造Google Maps的网页导航链接,点击门店1时触发导航:
function navigateToStore1() { // origin设为"current+location"会自动使用用户当前位置,也可替换为具体经纬度 const origin = "current+location"; // destination替换为门店1的经纬度或具体地址 const destination = "39.9042,116.4074"; // 示例经纬度,替换为门店1实际位置 const navUrl = `https://www.google.com/maps/dir/?api=1&origin=${origin}&destination=${destination}&travelmode=driving`; window.open(navUrl, '_blank'); }
将门店1的点击事件绑定到这个函数即可。
内容的提问来源于stack exchange,提问作者Fayakon
相关产品推荐
相关产品推荐

