【问题标题】:How to extract location name from lat and lon如何从纬度和经度中提取位置名称
【发布时间】:2018-11-26 15:58:10
【问题描述】:

我在颤振中使用地理定位插件提取了经度和纬度。但现在我需要根据这些经度和纬度创建地名。

我尝试使用地理编码器插件,但是

  final coordinates = new Coordinates(latitude, longitude);
          var addresses =  Geocoder.local.findAddressesFromCoordinates(coordinates);

      var first = addresses.first; 

上面的行给出错误,说没有为类 Future 定义 getter first

      print("${first.featureName} : ${first.addressLine}");

如何使用这些经纬度并在颤振中转换为地址?

【问题讨论】:

    标签: google-maps dart flutter flutter-dependencies


    【解决方案1】:

    findAddressesFromCoordinates 在这种情况下返回 Future

    你可以让你的函数或方法async:

    void yourFunction() async {
      final coordinates = new Coordinates(latitude, longitude);
      var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
    
      var first = addresses.first; 
      print("${first.featureName} : ${first.addressLine}");
    }
    

    在这种情况下,您需要在方法调用前使用await 关键字,这将使函数仅在之后您的对象使用地址继续运行已取回。

    另一种选择是在Future 上使用then 方法,如下所示:

    void yourFunction() {
      final coordinates = new Coordinates(latitude, longitude);
      Geocoder.local.findAddressesFromCoordinates(coordinates).then((addresses) {
        var first = addresses.first; 
        print("${first.featureName} : ${first.addressLine}");
      });
    }
    

    在这种情况下,您将回调传递给then 方法,一旦返回findAddressesFromCoordinates 的结果将在其中执行,但yourFunction 本身将继续运行。

    【讨论】:

      【解决方案2】:

      findAddressesFromCoordinates 方法返回Future<List<Address>>

      所以你可以使用 then

      final coordinates = new Coordinates(latitude, longitude);
      var addresses =  
      Geocoder.local.findAddressesFromCoordinates(coordinates).then(
      (data) => print(data);
      );
      

      或者你可以只使用 async/await :

      getAddressesFromCoordinates() async {
      final coordinates = new Coordinates(1.10, 45.50);
      addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
      first = addresses.first;
      print("${first.featureName} : ${first.addressLine}");}
      

      如果你想了解 dart 中异步编程的基础知识,你应该看看这个article

      【讨论】:

        【解决方案3】:

        在本地试试这个谷歌

        final coordinates = new Coordinates(position.latitude, position.longitude);  
        geocoder.google('GOOGLE_API_KEY').findAddressesFromCoordinates(coordinates)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-14
          • 1970-01-01
          • 1970-01-01
          • 2021-01-24
          • 2018-01-08
          • 1970-01-01
          • 2018-12-14
          • 1970-01-01
          相关资源
          最近更新 更多