在 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;

}

使用地理编码器插件您可以从Latitiude and penture

获得地址
 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;
    }

编辑

请使用地理编码代替地理编码器作为地理编码由BaseFlow.com代理商维护。

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

您必须从Goole Console生成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;
  }

in pubspec.yaml

geolocator: '^5.1.1'
  geocoder: ^0.2.1

导入此软件包

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}");
      }

2022年最佳方法。

地理编码器被弃用,将来将被删除。因此,使用地理编码并使用以下方法获取地址。

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;
  }

您需要使用"反向地理编码"服务,例如Google的API:https://developers.google.com/maps/documentation/geocoding/start。还有其他其他...只是Google用于"地理编码"。

更新:显然也有本地API。请参阅:https://pub.dartlang.org/packages/geocoder

我最近完成了它,您需要地理编码插件,然后导入此文件

import 'package:geocoding/geocoding.dart';

之后,我们必须创建方法。

getUserLocation(){
 List<Placemark> placemarks = await placemarkFromCoordinates(
        currentPostion.latitude, currentPostion.longitude);
    Placemark place = placemarks[0];
   print(place)
}

您可以访问所有属性,例如名称,使用place对象(例如place.name.name

)的局部性
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';
_getLocation() async {
GeolocationStatus geolocationStatus = await 
Geolocator().checkGeolocationPermissionStatus();
Position position = await Geolocator()
    .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
debugPrint('location: ${position.latitude}');

final coordinates = new Coordinates(position.latitude, position.longitude);
debugPrint('coordinates is: $coordinates');
var addresses =
    await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
// print number of retured addresses 
debugPrint('${addresses.length}');
// print the best address
debugPrint("${first.featureName} : ${first.addressLine}");
//print other address names
debugPrint(Country:${first.countryName} AdminArea:${first.adminArea} SubAdminArea:${first.subAdminArea}");
// print more address names
debugPrint(Locality:${first.locality}: Sublocality:${first.subLocality}");
}

由于上述答案中建议的地理编码器插件已过时,请使用地理定位器和地理编码插件

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

_getLocation() async
{
  Position position = await 
  Geolocator.getCurrentPosition(desiredAccuracy: 
    LocationAccuracy.high);
  debugPrint('location: ${position.latitude}');
  List<Placemark> addresses = await 
  placemarkFromCoordinates(position.latitude,position.longitude);
  var first = addresses.first;
  print("${first.name} : ${first..administrativeArea}");
}

查找地理编码酒吧链接地理编码摇摆

最新更新