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

20

我在Flutter中使用了位置插件,只能获取纬度经度。如何获取完整的地址详细信息?下面是代码。

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;



}

我们如何获取经度和纬度? - Nithin Sai
8个回答

29

通过使用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,因为Geocodingbaseflow.com维护。


2
https://github.com/Lyokone/flutterlocation/blob/master/CHANGELOG.md So you'd need to either change all your Map types to LocationData or set your plugin version to ^1.4.0.``` - BIS Tech
谢谢,我会去看看。 - Arun
有没有免费的服务可以将地图地址转换为经纬度,经纬度转换为地址和提供地点自动完成?请推荐。非常感谢。 - Kamlesh
我已经尝试了你的答案,但 geocoder 插件不是空安全的,该怎么解决这个问题呢? - Ravindra S. Patil
1
地理编码器现在已经弃用。如果您尝试使用pubspec.yaml导入此插件,将会出现以下错误。 插件“geocoder”使用了一个废弃的Android嵌入版本。 为避免意外的运行时故障或未来的构建故障,请尝试查看此插件是否支持Android V2嵌入。否则,考虑删除它,因为Flutter的未来版本将删除这些已弃用的API。 - A.Ktns
显示剩余3条评论

12

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

您需要从Google控制台生成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;
  }

1
有没有办法将地址拆分成邮编、街道和州等部分? - IamVariable

11

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

地理编码器现已过时。 - Matt Booth

4

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

尝试过这个方法,但是我进行了修改,使得我不必获取用户的当前位置。相反,determinePosition() 接受一个 GeoPoint 输入,其中包含纬度和经度组件。它在开始时工作正常,但当我尝试移动我的相机(也会改变传递的 GeoPoint)时,我开始收到 null 值。这可能是由于 GeoCode 限制了对应用程序的查询所致吗?这是我的问题:https://stackoverflow.com/questions/75774109/geocode-responds-very-slow-even-in-camera-idle-querries-in-android-flutter-googl - lambduh

3

我最近做了这件事。您需要GeoCoding插件,然后导入此文件。

import 'package:geocoding/geocoding.dart';

创建方法之前,我们需要进行如下操作。
getUserLocation(){
 List<Placemark> placemarks = await placemarkFromCoordinates(
        currentPostion.latitude, currentPostion.longitude);
    Placemark place = placemarks[0];
   print(place)
}

您可以通过place对象访问所有属性,例如name、locality,如place.name。


3

有没有免费的服务可用于将地图地址转换为经纬度,经纬度转换为地址以及提供地点自动完成?请给予建议。非常感谢。 - Kamlesh
这种情况十分不太可能,因为没有任何盈利机制,所以只能出于慈善之心去完成。 - Randal Schwartz

1

由于上面回答中建议的地理编码器插件已经过时,请使用 geolocator 和 geocoding 插件。

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

查找地理编码公共链接 Flutter 地理编码


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接