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

slhcrj9b  于 2022-11-26  发布在  Flutter
关注(0)|答案(8)|浏览(141)

我已经在flutter中使用了location插件,我只能得到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;


}
6ojccjat

6ojccjat1#

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

编辑

请使用Geocoding而不是Geocoder,因为地理编码baseflow.com代理维护。

px9o7tmv

px9o7tmv2#

在公共规范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}");
      }
dphi5xsq

dphi5xsq3#

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

您必须从Goole控制台生成古勒Map API密钥[需要登录]Generate API Key From Here

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

yv5phkfx4#

您需要使用“反向地理编码”服务,例如Google的API:https://developers.google.com/maps/documentation/geocoding/start .还有其他的也在那里...只是谷歌一下“地理编码”。
更新:显然也有一个本地API。https://pub.dartlang.org/packages/geocoder

vojdkbi0

vojdkbi05#

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

ergxz8rk6#

I had it recently You need GeoCoding Plugin(我最近才完成此操作),然后导入此文件

import 'package:geocoding/geocoding.dart';

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

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

您可以使用像www.example.com这样的地点对象访问所有属性,如名称、地点place.name

4urapxun

4urapxun7#

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

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

查找地理编码发布链接geocoding flutter

deikduxw

deikduxw8#

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

相关问题