在 Flutter 中根据当前位置的经纬度获取完整地址详细信息

Aru*_*run 10 android flutter

我已经在flutter 中使用了位置插件,我只能得到和。如何获取完整的地址详细信息。代码如下。latitudelongitude

Future<Map<String, double>> _getLocation() async {
//var currentLocation = <String, double>{};
Map<String,double> currentLocation;
try {
  currentLocation = await location.getLocation();
} catch (e) {
  currentLocation = null;
}
setState(() {
  userLocation = currentLocation;
});
return currentLocation;



}
Run Code Online (Sandbox Code Playgroud)

Har*_*llu 19

使用Geocoder插件,您可以从纬度和经度获取地址

 import 'package:location/location.dart';
 import 'package:geocoder/geocoder.dart';
 import 'package:flutter/services.dart';

getUserLocation() async {//call this async method from whereever you need
    
      LocationData myLocation;
      String error;
      Location location = new Location();
      try {
        myLocation = await location.getLocation();
      } on PlatformException catch (e) {
        if (e.code == 'PERMISSION_DENIED') {
          error = 'please grant permission';
          print(error);
        }
        if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
          error = 'permission denied- please enable it from app settings';
          print(error);
        }
        myLocation = null;
      }
      currentLocation = myLocation;
      final coordinates = new Coordinates(
          myLocation.latitude, myLocation.longitude);
      var addresses = await Geocoder.local.findAddressesFromCoordinates(
          coordinates);
      var first = addresses.first;
      print(' ${first.locality}, ${first.adminArea},${first.subLocality}, ${first.subAdminArea},${first.addressLine}, ${first.featureName},${first.thoroughfare}, ${first.subThoroughfare}');
      return first;
    }
Run Code Online (Sandbox Code Playgroud)

编辑

请使用地理编码,而不是地理编码器作为地理编码是维护baseflow.com机构。

  • ``看起来教程是使用旧版本的位置插件完成的,从 v2.0.0 开始,他们更改了 api 以返回结构化数据而不是地图。https://github.com/Lyokone/flutterlocation/blob/master/CHANGELOG.md 因此,您需要将所有 Map&lt;String, double&gt; 类型更改为 LocationData 或将插件版本设置为 ^1.4.0。 `` (2认同)

Som*_*ath 13

这是使用 Google API 从当前位置或任何纬度和经度获取地址的最简单方法。

您必须从 Goole 控制台生成 Goole Map API 密钥 [需要登录] 从此处生成 API 密钥

  getAddressFromLatLng(context, double lat, double lng) async {
    String _host = 'https://maps.google.com/maps/api/geocode/json';
    final url = '$_host?key=$mapApiKey&language=en&latlng=$lat,$lng';
    if(lat != null && lng != null){
      var response = await http.get(Uri.parse(url));
      if(response.statusCode == 200) {
        Map data = jsonDecode(response.body);
        String _formattedAddress = data["results"][0]["formatted_address"];
        print("response ==== $_formattedAddress");
        return _formattedAddress;
      } else return null;
    } else return null;
  }
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法获得分割地址,例如邮政编码、街道状态等? (2认同)

小智 10

在 pubspec.yaml 中

geolocator: '^5.1.1'
  geocoder: ^0.2.1
Run Code Online (Sandbox Code Playgroud)

导入这个包

import 'package:geolocator/geolocator.dart';
import 'package:geocoder/geocoder.dart';


_getLocation() async
      {
        Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
        debugPrint('location: ${position.latitude}');
        final coordinates = new Coordinates(position.latitude, position.longitude);
        var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
        var first = addresses.first;
        print("${first.featureName} : ${first.addressLine}");
      }
Run Code Online (Sandbox Code Playgroud)


小智 6

2022 年的最佳方法。

GeoCoder 已弃用,并将在将来删除。因此,使用 GeoCode 并使用以下方法来获取地址。

import 'package:geocode/geocode.dart';
import 'package:geolocator/geolocator.dart';

Future<Address> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;
    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    final currentLocation = await Geolocator.getCurrentPosition();
    final currentAddress = await GeoCode().reverseGeocoding(
        latitude: currentLocation.latitude,
        longitude: currentLocation.longitude);
    return currentAddress;
  }
Run Code Online (Sandbox Code Playgroud)