dart Flutter -从坐标获取地理编码地址

lawou6xi  于 2023-01-03  发布在  Flutter
关注(0)|答案(7)|浏览(254)

我已经实现了一个可靠的方法来获得用户的纬度,经度坐标在我创建的应用程序,但似乎不能把这些坐标变成一个地标。
我还想弄清楚我需要使用什么来打印这些数据。
这就是我想要得到的数据:

List<Placemark> place = [];

void _getPlace() async {
  List<Placemark> newPlace = await _geolocator.placemarkFromCoordinates(_position.latitude, _position.longitude);
  print(newPlace);
  setState(() {
    place = newPlace;
  });
}

谢啦,谢啦
编辑:
CopsOnRoad的响应后,我得到这个错误:

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: 

NoSuchMethodError: The method 'placemarkFromCoordinates' was called on null.
Receiver: null
Tried calling: placemarkFromCoordinates(51.4998, -0.129)
#0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:50:5)
#1      _NearbyPageState._getPlace 
package:tr/pages/nearby.dart:128
<asynchronous suspension>
#2      _NearbyPageState._controlCard.<anonymous closure> 
package:tr/pages/nearby.dart:629
#3      GestureRecognizer.invokeCallback 
package:flutter/…/gestures/recognizer.dart:182
#4      TapGestureRecognizer._checkUp 
package:flutter/…/gestures/tap.dart:365
#5      TapGestureRecognizer.acceptGesture 
package:flutter/…/gestures/tap.dart:312
#6      GestureArenaManager.sweep 
package:flutter/…/gestures/arena.dart:156
#7      _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent 
package:flutter/…/gestures/binding.dart:222
#8      _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (p<…>
eeq64g8w

eeq64g8w1#

**更新:**使用geocoding

import 'package:geocoding/geocoding.dart';

List<Placemark> placemarks = await placemarkFromCoordinates(52.2165157, 6.9437819);

旧解决方案:

你已经在那里,你需要额外的东西是:

String _address = ""; // create this variable

void _getPlace() async {
  List<Placemark> newPlace = await _geolocator.placemarkFromCoordinates(_position.latitude, _position.longitude);

  // this is all you need
  Placemark placeMark  = newPlace[0]; 
  String name = placeMark.name;
  String subLocality = placeMark.subLocality;
  String locality = placeMark.locality;
  String administrativeArea = placeMark.administrativeArea;
  String postalCode = placeMark.postalCode;
  String country = placeMark.country;
  String address = "${name}, ${subLocality}, ${locality}, ${administrativeArea} ${postalCode}, ${country}";
  
  print(address);

  setState(() {
    _address = address; // update _address
  });
}
ukxgm1gy

ukxgm1gy2#

从版本6.0.0开始,从geolocator中删除了位置标记,并将其移至geocoding
从版本6.0.0开始,地理编码功能(placemarkFromAddress和placemarkFromCoordinates)不再是地理定位器插件的一部分。我们已将这些功能移到它们自己的插件中:这个新插件是旧方法的改进版本。
使用地理编码将纬度和经度转换为地址

List<Placemark> placemarks = await placemarkFromCoordinates(52.2165157, 6.9437819);
yquaqz18

yquaqz183#

使用pub.dev flutter_地理编码
https://pub.dev/packages/flutter_geocoding

我已经使用了swift的GMSGeocoder和java的android.location.Geocoder,并将其应用到flutter中,我认为它比pub.dev中的库Geocode效率更高。
我的示例代码
地理编码库java和swift自加
java

@Override
 public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        super.configureFlutterEngine(flutterEngine);

        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "samples.flutter.dev/latlng")
                .setMethodCallHandler(
                        (call, result) -> {

                            double lat = call.argument("lat");
                            double lng = call.argument("lng");
                            result.success("return value lat and lng");

                        }
                );
    }

雨燕

override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
        let batteryChannel = FlutterMethodChannel(name: "samples.flutter.dev/latlng",
                                                  binaryMessenger: controller.binaryMessenger)
        
        batteryChannel.setMethodCallHandler({
            [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
            
            // Note: this method is invoked on the UI thread.
            guard call.method == "latlng" else {
                result(FlutterMethodNotImplemented)
                return
            }
            
            self?.latlng(call,result: result)
        })
        GMSServices.provideAPIKey("")
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    private func latlng(_ call: FlutterMethodCall,result:FlutterResult) {
        if let args = call.arguments as? Dictionary<String, Any>,
           let lat = args["lat"] as? Double ,let lng = args["lng"] as? Double  {
            result("return latlng result" )
          } else {
            result(FlutterError.init(code: "bad args", message: nil, details: nil))
          }
    }

Flutter

Future<void> _getBatteryLevel(double a, double b) async {
  String latlng;
  try {
    final String result = await const MethodChannel('samples.flutter.dev/latlng').invokeMethod(
        'latlng', <String, dynamic>{"lat": a, "lng": b});
    latlng = result;
  } on PlatformException catch (e) {
    latlng = "Failed to get latlng level: '${e.message}'.";
  }
}
baubqpgj

baubqpgj4#

首先,您已经包含了lib -geolocator:^3.0.1,在公共质量标准yaml中

///Get current location
  Geolocator _geolocator = Geolocator();
  String latitude = "";
  String longitude = "";
  String address = "";

试试这个解决方案-

///Call this function
 _fetchLocation() async {
    Position position = await _geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.best);///Here you have choose level of distance
    latitude = position.latitude.toString() ?? '';
    longitude = position.longitude.toString() ?? '';
    var placemarks = await _geolocator.placemarkFromCoordinates(position.latitude, position.longitude);
    address ='${placemarks.first.name.isNotEmpty ? placemarks.first.name + ', ' : ''}${placemarks.first.thoroughfare.isNotEmpty ? placemarks.first.thoroughfare + ', ' : ''}${placemarks.first.subLocality.isNotEmpty ? placemarks.first.subLocality+ ', ' : ''}${placemarks.first.locality.isNotEmpty ? placemarks.first.locality+ ', ' : ''}${placemarks.first.subAdministrativeArea.isNotEmpty ? placemarks.first.subAdministrativeArea + ', ' : ''}${placemarks.first.postalCode.isNotEmpty ? placemarks.first.postalCode + ', ' : ''}${placemarks.first.administrativeArea.isNotEmpty ? placemarks.first.administrativeArea : ''}';
    print("latitude"+latitude);
    print("longitude"+longitude);
    print("adreess"+address);
  }
4smxwvx5

4smxwvx55#

try {
    await Geolocator()
        .placemarkFromCoordinates(value[0], value[1])
        .then((result) {
      Placemark placeMark = result[0];
      String name = placeMark.name;
      String subLocality = placeMark.subLocality;
      String locality = placeMark.locality;
      String administrativeArea = placeMark.administrativeArea;
      String postalCode = placeMark.postalCode;
      String country = placeMark.country;
      String address =
          "${name}, ${subLocality}, ${locality}, ${administrativeArea} ${postalCode}, ${country}";
      print(address);
      
    });
  } on PlatformException catch (e) {
    print(e);
  }
2o7dmzc5

2o7dmzc56#

使用Geolocator Plugin新版本(从版本6.0.0开始)。地理编码功能(placemarkFromAddressplacemarkFromCoordinates)不再是geolocator插件的一部分。此方法已将这些功能移至其自己的插件:geocoding

slhcrj9b

slhcrj9b7#

未来getLatAndlong()异步{cl =等待地理定位器. getCurrentPosition(). then((值)=〉值);

lat = cl.latitude;
long = cl.longitude;
_kGooglePlex =    CameraPosition(
    target: LatLng(lat,long),
    zoom:14
);
List<Placemark> placemarks = await placemarkFromCoordinates(
    lat, long);
print("country"+placemarks[0].country!);
print("area"+placemarks[0].administrativeArea!);
print("locality"+placemarks[0].locality!);
print("sublocality"+placemarks[0].subLocality!);
print("postlocality"+placemarks[0].postalCode!);
print("street"+placemarks[0].street!);

setState(() {

  countrycurrent = placemarks[0].country!;
  localcurrent = placemarks[0].administrativeArea!;
  madinacurrent = placemarks[0].subLocality!;
  curren=countrycurrent+","+localcurrent+","+madinacurrent;
});

mymarker.add(标记(信息窗口:信息窗口(标题:地标[0].国家!+"",+地标[0].管理区域!+"",+地标[0].位置!),可拖动:真的,

icon:
  BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueOrange),

  markerId: MarkerId("4"),

  position: LatLng(lat, long)),

);}

相关问题