8

I've implemented a reliable way of getting user lat,long coordinates in an app I'm creating, but can't seem to turn these coordinates into a placemark.

I'd also like to figure out what I need to use to print this data.

This is what I'm trying to get this data with:

List<Placemark> place = [];

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

Thanks

Edit:

After CopsOnRoad's response, I'm getting this error:

[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<…>
4
  • Have you added required permission in info.plist to use locations on iPhone?
    – Mahendra
    Sep 16, 2019 at 5:31
  • Yeah, I have permissions in plist
    – Jake
    Sep 16, 2019 at 8:17
  • What newPlace prints?
    – CopsOnRoad
    Sep 18, 2019 at 17:05
  • Something like [Instance of ‘Placemark’]
    – Jake
    Sep 18, 2019 at 17:05

7 Answers 7

28
+50

Update: Use geocoding

import 'package:geocoding/geocoding.dart';

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

Old solution:

You are already there, extra stuff that you need is:

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
  });
}
6
  • Also, there may be a certain way to print this I'm not getting but I doubt that as you've got print(address) above in _getPlace()
    – Jake
    Sep 18, 2019 at 18:16
  • Just fixed my issue after a flutter clean
    – Jake
    Sep 18, 2019 at 19:22
  • how do you handle over_query_limit exception? Aug 7, 2020 at 8:57
  • 1
    geocoding suports just english?! i want have address result with local languages. how can I do this? Mar 13, 2021 at 13:33
  • 1
    Is there any free service to use map address to lat-long, lat-long to address and place autocomplete provider? Kindly suggest. Thanks a lot.
    – Kamlesh
    May 21, 2021 at 13:19
6

Placemark has been removed from geolocator starting from version 6.0.0 and moved to geocoding.

Starting from version 6.0.0 the geocoding features (placemarkFromAddress and placemarkFromCoordinates) are no longer part of the geolocator plugin. We have moved these features to their own plugin: geocoding. This new plugin is an improved version of the old methods.

To translate latitude and longitude into an address with geocoding use

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

Use pub.dev flutter_geocoding

https://pub.dev/packages/flutter_geocoding

OR

I have used swift 'GMSGeocoder' and java 'android.location.Geocoder' and applied it to flutter.I think it is more efficient than the library Geocode in pub.dev.

My example code

Geocode library java and swift add by yourself

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

                        }
                );
    }

swift

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}'.";
  }
}
4

first, you have include lib -geolocator: ^3.0.1 in pubspec.yaml

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

Try this solution -

///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);
  }
3
 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);
  }
2

With Geolocator Plugin new version (from version 6.0.0). Geocoding features (placemarkFromAddress and placemarkFromCoordinates) are no longer part of the geolocator plugin. This method have moved these features to their own plugin: geocoding

0
1

Future getLatAndlong() async{ cl = await Geolocator.getCurrentPosition().then((value)=>value);

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( Marker( infoWindow: InfoWindow( title: placemarks[0].country! + "," + placemarks[0].administrativeArea! + "," + placemarks[0].locality! ), draggable: true,

  icon:
  BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueOrange),

  markerId: MarkerId("4"),

  position: LatLng(lat, long)),

);}

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Feb 14, 2022 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.