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

Flutter中如何获取Geocoding返回位置列表中的Latitude纬度值

问题原因

locationFromAddress 方法返回的是 geocoding 插件定义的 Location 类型对象组成的列表,你执行 locations[0] 时拿到的是列表内的第一个 Location 类实例,不是可按下标拆分的数组/键值对Map,因此无法直接通过索引拆分出单独的纬度字段,需要通过实例的公开属性访问对应值。

正确提取方式

直接访问 Location 实例内置的 latitude 属性即可拿到纬度值,修正后的代码如下:

Future fetchAlbum() async{
  List locations = await locationFromAddress("New Delhi, India");
  // 提取第一个匹配位置的纬度
  num latitude = locations[0].latitude;
  // 同理可提取其他属性:
  // num longitude = locations[0].longitude;
  // DateTime timestamp = locations[0].timestamp;
  print(latitude); // 输出结果:28.6139391
}
鲁棒性优化建议

正式业务场景下建议增加空结果判断,避免地址解析无匹配结果时触发下标越界报错:

Future fetchAlbum() async{
  List locations = await locationFromAddress("New Delhi, India");
  if (locations.isNotEmpty) {
    final firstLocation = locations.first;
    final lat = firstLocation.latitude;
    final lng = firstLocation.longitude;
    print("解析成功,纬度:$lat,经度:$lng");
  } else {
    print("当前地址未解析到有效坐标");
  }
}

内容的提问来源于stack exchange,提问作者Rahul Sahni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:09:20