带有地理编码器包,flutter,dart,flutter-packages"/>

首页 > 解决方案 > 颤振——带有地理编码器包

问题描述

我需要从经度和纬度中获取城市名称。我没有找到一个包来做到这一点,所以我使用 location 包来获取 Long 和 Lat 并使用地理编码器来获取城市名称。

但我一直有这个错误并且没有结果:

[错误:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:PlatformException(失败,失败,空,空)

而这之后在控制台上:<异步挂起>

这是我的代码:

class _ProfileScreenState extends State<ExploreScreen> {
  dynamic currentLocation;
  double userLongitude;
  double userLatitude;
  Coordinates coordinates;
  var addresses;
  var first;

  @override
  initState() {
    super.initState();
    _getCurrentLongAndLat();
    _getCurrentPosition(userLatitude, userLatitude);
  }

  Future _getCurrentLongAndLat() async {
    currentLocation = LocationData;
    var error;
    var location = new Location();

    try {
      currentLocation = await location.getLocation();
      userLatitude = currentLocation.latitude;
      userLongitude = currentLocation.longitude;
      print('$userLatitude $userLatitude');
    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        error = 'Permission denied';
      }
      currentLocation = null;
    }
  }

  Future _getCurrentPosition(double long, double lat) async {
    coordinates = new Coordinates(userLatitude, userLongitude);
    addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
    print(addresses.first);
  }
}

标签: flutterdartflutter-packages

解决方案


我意识到颤振包地理定位器和位置有时会相互冲突。

尝试使用地理定位器获取您当前的位置:

Future _getCurrentPosition() async {
    Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high).then((Position position) {
      setState(() {
        _currentPosition = position;
        userLongitude = position.longitude;
        userLatitude = position.latitude;
        
      });
    });
  }

它是一个 Future,因此您可以使用 await 来真正等待结果,然后使用 userLat 和 userLng 调用 getAddress 函数。


推荐阅读