从地址抖动中获取坐标

2024-01-06

有人可以指导我在 flutter 中获取地址的坐标吗?

我需要在文本框中输入地址并获取该地址的经度和纬度


您可以复制粘贴运行下面的完整代码
您可以使用包https://pub.dev/packages/geocoder https://pub.dev/packages/geocoder

代码片段

import 'package:geocoder/geocoder.dart';

// From a query
final query = "1600 Amphiteatre Parkway, Mountain View";
var addresses = await Geocoder.local.findAddressesFromQuery(query);
var first = addresses.first;
print("${first.featureName} : ${first.coordinates}");

工作演示,最后一行是坐标

完整代码

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geocoder/services/base.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class AppState extends InheritedWidget {
  const AppState({
    Key key,
    this.mode,
    Widget child,
  })  : assert(mode != null),
        assert(child != null),
        super(key: key, child: child);

  final Geocoding mode;

  static AppState of(BuildContext context) {
    return context.inheritFromWidgetOfExactType(AppState);
  }

  @override
  bool updateShouldNotify(AppState old) => mode != old.mode;
}

class GeocodeView extends StatefulWidget {
  GeocodeView();

  @override
  _GeocodeViewState createState() => new _GeocodeViewState();
}

class _GeocodeViewState extends State<GeocodeView> {
  _GeocodeViewState();

  final TextEditingController _controller = new TextEditingController();

  List<Address> results = [];

  bool isLoading = false;

  Future search() async {
    this.setState(() {
      this.isLoading = true;
    });

    try {
      var geocoding = AppState.of(context).mode;
      var results = await geocoding.findAddressesFromQuery(_controller.text);
      this.setState(() {
        this.results = results;
      });
    } catch (e) {
      print("Error occured: $e");
    } finally {
      this.setState(() {
        this.isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Column(children: <Widget>[
      new Card(
        child: new Padding(
          padding: const EdgeInsets.all(10.0),
          child: new Row(
            children: <Widget>[
              new Expanded(
                child: new TextField(
                  controller: _controller,
                  decoration: new InputDecoration(hintText: "Enter an address"),
                ),
              ),
              new IconButton(
                  icon: new Icon(Icons.search), onPressed: () => search())
            ],
          ),
        ),
      ),
      new Expanded(child: new AddressListView(this.isLoading, this.results)),
    ]);
  }
}

class ReverseGeocodeView extends StatefulWidget {
  ReverseGeocodeView();

  @override
  _ReverseGeocodeViewState createState() => new _ReverseGeocodeViewState();
}

class _ReverseGeocodeViewState extends State<ReverseGeocodeView> {
  final TextEditingController _controllerLongitude =
      new TextEditingController();
  final TextEditingController _controllerLatitude = new TextEditingController();

  _ReverseGeocodeViewState();

  List<Address> results = [];

  bool isLoading = false;

  Future search() async {
    this.setState(() {
      this.isLoading = true;
    });

    try {
      var geocoding = AppState.of(context).mode;
      var longitude = double.parse(_controllerLongitude.text);
      var latitude = double.parse(_controllerLatitude.text);
      var results = await geocoding
          .findAddressesFromCoordinates(new Coordinates(latitude, longitude));
      this.setState(() {
        this.results = results;
      });
    } catch (e) {
      print("Error occured: $e");
    } finally {
      this.setState(() {
        this.isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Column(children: <Widget>[
      new Card(
        child: new Padding(
          padding: const EdgeInsets.all(10.0),
          child: new Row(
            children: <Widget>[
              new Expanded(
                child: new Column(
                  children: <Widget>[
                    new TextField(
                      controller: _controllerLatitude,
                      decoration: new InputDecoration(hintText: "Latitude"),
                    ),
                    new TextField(
                      controller: _controllerLongitude,
                      decoration: new InputDecoration(hintText: "Longitude"),
                    ),
                  ],
                ),
              ),
              new IconButton(
                  icon: new Icon(Icons.search), onPressed: () => search())
            ],
          ),
        ),
      ),
      new Expanded(child: new AddressListView(this.isLoading, this.results)),
    ]);
  }
}

class _MyAppState extends State<MyApp> {
  Geocoding geocoding = Geocoder.local;

  final Map<String, Geocoding> modes = {
    "Local": Geocoder.local,
    "Google (distant)": Geocoder.google("<API-KEY>"),
  };

  void _changeMode(Geocoding mode) {
    this.setState(() {
      geocoding = mode;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new AppState(
      mode: this.geocoding,
      child: new MaterialApp(
        home: new DefaultTabController(
          length: 2,
          child: new Scaffold(
            appBar: new AppBar(
              title: new Text('Geocoder'),
              actions: <Widget>[
                new PopupMenuButton<Geocoding>(
                  // overflow menu
                  onSelected: _changeMode,
                  itemBuilder: (BuildContext context) {
                    return modes.keys.map((String mode) {
                      return new CheckedPopupMenuItem<Geocoding>(
                        checked: modes[mode] == this.geocoding,
                        value: modes[mode],
                        child: new Text(mode),
                      );
                    }).toList();
                  },
                ),
              ],
              bottom: new TabBar(
                tabs: [
                  new Tab(
                    text: "Query",
                    icon: new Icon(Icons.search),
                  ),
                  new Tab(
                    text: "Coordinates",
                    icon: new Icon(Icons.pin_drop),
                  ),
                ],
              ),
            ),
            body: new TabBarView(children: <Widget>[
              new GeocodeView(),
              new ReverseGeocodeView(),
            ]),
          ),
        ),
      ),
    );
  }
}

class AddressTile extends StatelessWidget {
  final Address address;

  AddressTile(this.address);

  final titleStyle =
      const TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold);

  @override
  Widget build(BuildContext context) {
    return new Padding(
      padding: const EdgeInsets.all(10.0),
      child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new ErrorLabel(
              "feature name",
              this.address.featureName,
              fontSize: 15.0,
              isBold: true,
            ),
            new ErrorLabel("address lines", this.address.addressLine),
            new ErrorLabel("country name", this.address.countryName),
            new ErrorLabel("locality", this.address.locality),
            new ErrorLabel("sub-locality", this.address.subLocality),
            new ErrorLabel("admin-area", this.address.adminArea),
            new ErrorLabel("sub-admin-area", this.address.subAdminArea),
            new ErrorLabel("thoroughfare", this.address.thoroughfare),
            new ErrorLabel("sub-thoroughfare", this.address.subThoroughfare),
            new ErrorLabel("postal code", this.address.postalCode),
            this.address.coordinates != null
                ? new ErrorLabel("", this.address.coordinates.toString())
                : new ErrorLabel("coordinates", null),
          ]),
    );
  }
}

class AddressListView extends StatelessWidget {
  final List<Address> addresses;

  final bool isLoading;

  AddressListView(this.isLoading, this.addresses);

  @override
  Widget build(BuildContext context) {
    if (this.isLoading) {
      return new Center(child: new CircularProgressIndicator());
    }

    return new ListView.builder(
      itemCount: this.addresses.length,
      itemBuilder: (c, i) => new AddressTile(this.addresses[i]),
    );
  }
}

class ErrorLabel extends StatelessWidget {
  final String name, text;

  final TextStyle descriptionStyle;

  ErrorLabel(this.name, String text,
      {double fontSize = 9.0, bool isBold = false})
      : this.text = text ?? "Unknown $name",
        this.descriptionStyle = new TextStyle(
            fontSize: fontSize,
            fontWeight: isBold ? FontWeight.bold : FontWeight.normal,
            color: text == null ? Colors.red : Colors.black);

  @override
  Widget build(BuildContext context) {
    return new Text(this.text, style: descriptionStyle);
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从地址抖动中获取坐标 的相关文章

随机推荐

  • 我正在使用 django table 2 并尝试按照官方文档导出我的表

    我已遵循 django table 2 的官方文档 但它不起作用 我不知道为什么 views py from django shortcuts import render from django tables2 import Request
  • scala 中缩进保留字符串插值

    我想知道在 scala 中进行字符串插值时是否有任何方法可以保留缩进 本质上 我想知道是否可以插入我自己的 StringContext 宏可以解决这个问题 但我想等到它们正式发布 这就是我要的 val x line1 nline2 val
  • 如何从数组中获取多个随机元素?

    我正在研究 如何从 JavaScript 数组中随机访问元素 我发现了很多与此相关的链接 喜欢 从 JavaScript 数组中获取随机项 https stackoverflow com questions 5915096 get rand
  • laravel 使用 google 帐户登录

    我正在制作一个应用程序 我希望用户使用他们的谷歌帐户登录 我有用户 oauth 4 laravel 并且我有这个 用户控制器 php get data from input code Input get code get google se
  • Android 代码截图。明白了,但还不完美

    我正在尝试在 Android 中的代码中截取屏幕截图 实际上 屏幕截图是主RelativeLayout 的位图 屏幕截图已拍摄 但内容显示错误 不遵守 fill parent 等标签 并且图像显示在左上角并具有原始大小 请任何人帮忙 Tha
  • Firefox 在提交按钮中添加 2px 内边距

    您好 我似乎在 Firefox 在提交按钮中添加 2 个额外像素的填充时遇到了一些问题 我已经在 chrome 和 IE9 中对此进行了测试 两种浏览器都可以正常渲染代码 Firefox 似乎在底部添加了 2 个像素填充提交按钮 右上角有钥
  • realloc会对旧指针做什么[重复]

    这个问题在这里已经有答案了 我有一个关于 realloc 函数的问题 应用realloc函数后旧指针的内容会改变吗 代码是 main int a b i a calloc 5 sizeof int for i 0 i lt 5 i a i
  • Android 视图上的投影

    我已经对此进行了一些广泛的代码示例搜索 但找不到任何内容 特别是 我希望向在 ImageView 中使用的 png 可绘制对象添加阴影 这个 png 可绘制对象是一个带有透明角的圆角矩形 有人可以提供一个代码示例 说明如何在代码或 XML
  • Firestore 安全规则 .hasAny(['A', 'B', 'C']) 仍然可以使用吗?

    似乎无法使用 Firestore 安全规则 hasAny 此方法是否已弃用或不再可用 我用它就像 Functions NOT WORKING function isTeamMember teamId userId return get da
  • 从地址抖动中获取坐标

    有人可以指导我在 flutter 中获取地址的坐标吗 我需要在文本框中输入地址并获取该地址的经度和纬度 您可以复制粘贴运行下面的完整代码您可以使用包https pub dev packages geocoder https pub dev
  • 用于命名空间限定的 C++ 预处理器标记粘贴

    我在 gcc 4 7 1 std c 11 中的预处理器标记粘贴运算符上遇到问题 即 考虑以下代码 Create a name for a global map this works define GLOBAL MAP name g map
  • 将 ZipOutputStream 返回到浏览器

    我有一个 ZipOutputStream 我想将其返回到浏览器 我想要的体验是用户单击锚标记 然后为我拥有的 ZipOutputStream 显示文件下载提示 如何将 ZipOutputStream 返回到浏览器 昨天必须做同样的事情 By
  • 为什么 Oracle 表/列/索引名称限制为 30 个字符?

    我可以理解 很多年前会有这种限制 但现在这个限制肯定可以很容易地增加 我们有对象的命名约定 但总会出现达到此限制的情况 特别是在命名外键时 有谁真正知道为什么这不是更大的尺寸 或者是 11 克更大 显然 答案是它将破坏当前未进行防御性编码的
  • JavaScript - 二分搜索每次都会挂起

    我有一个二维数组 如下所示 1 11 23 2 22 52 3 33 61 其中数组按每行中的第一个值排序 我试图在数组中找到一个值close到搜索值 在一定的灵敏度内 这种设置的方式以及灵敏度的值确保数组中只有一个可能的匹配 搜索值是鼠标
  • 将拟合摘要写入 pdf 文件或类似文件中

    我正在循环中对许多数据集进行线性拟合 并将结果绘制在 pdf 文件中 是否可以直接将summary fit 的输出保存在同一个pdf文件中 而不是通过控制台观察大约100个数据集的摘要 LMmodel lt y x fit lt lm LM
  • 我什么时候应该使用前进和移动?

    我有一个对向量进行操作的代码 template
  • PHP:将任何浮点数格式化为十进制扩展

    我想创建一个函数formatFloat 它接受任何浮点并将其格式化为十进制扩展字符串 例如 formatFloat 1 0E 25 10 000 000 000 000 000 000 000 000 formatFloat 1 0E 24
  • 如何将两个 long 相除并得到值?

    我需要计算整数和长整数的概率 但我总是得到0 整数a 234 长b 123453344L 浮动 c a b 如何在 Java 中得到正确的结果 您需要将其中一个投射为float 或将其中一个变量声明为float从头开始 否则 Java 的整
  • 何时适合在 Web 项目中使用 UUID?

    我正忙于一个新项目的数据库设计 我不确定是否使用UUID或普通的表唯一自增id 到目前为止 我建立的网站都在一台服务器上运行 非常大的流量从来都不是太令人担忧的问题 然而 这个 Web 应用程序最终将在多个服务器上同时运行 提供 API 并
  • 自定义控件中的膨胀布局 - 如何?

    我有关于如何在这里创建自定义控件的想法 Android 界面 需要有关使用哪些小部件的建议 https stackoverflow com questions 5891153 android interface need suggestio