You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Google Maps导航函数的经纬度参数传递问题

解决Google Maps导航路线问题

首先你的openMap函数存在两个问题:参数类型定义错误,以及使用的是搜索URL而非导航路线URL。以下是修正后的实现:

修正后的代码

// 自定义函数:通过Google Maps应用打开从客户位置到卖家位置的导航路线
Future<void> openMap(double customerLat, double customerLng, double sellerLat, double sellerLng) async {
  // 使用Google Maps Directions API构造导航URL
  String googleUrl = 'https://www.google.com/maps/dir/?api=1&origin=$customerLat,$customerLng&destination=$sellerLat,$sellerLng';

  if (await canLaunchUrlString(googleUrl)) {
    await launchUrlString(googleUrl);
  } else {
    throw '无法打开Google Maps:$googleUrl';
  }
}

@override
void initState() {
  super.initState();
  custLocation();
}

关键修改说明

  • 参数修正:把错误的List<CustAddressModel>类型参数,改成四个double类型的参数,分别对应客户位置的纬度、经度,以及卖家位置的纬度、经度。
  • URL替换:将原搜索URL替换为导航路线URL,通过origin指定起点(客户位置),destination指定终点(卖家位置),这样Google Maps会直接展示两点间的导航路线。

调用方式

在按钮的点击事件中调用该函数,传入从数据库获取到的经纬度即可:

ElevatedButton(
  onPressed: () async {
    // 假设从数据库获取到的经纬度存在以下变量中
    double customerLat = 31.2304; // 客户纬度
    double customerLng = 121.4737; // 客户经度
    double sellerLat = 31.2165; // 卖家纬度
    double sellerLng = 121.4365; // 卖家经度

    try {
      await openMap(customerLat, customerLng, sellerLat, sellerLng);
    } catch (e) {
      print(e);
      // 这里可以添加错误提示,比如弹出Toast或SnackBar
    }
  },
  child: const Text('导航至卖家位置'),
)

注意事项

  • 确保已在pubspec.yaml中添加url_launcher依赖,并执行flutter pub get。
  • Android端需在AndroidManifest.xml中添加相关权限配置,确保能检测到Google Maps应用;iOS端需在Info.plist中添加LSApplicationQueriesSchemes,包含googlemaps和comgooglemaps。

内容的提问来源于stack exchange,提问作者Unknown Programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:42:47