Search code examples
flutterdartgeocoding

How to use locationFromAddress in flutter


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

how to replace placemarkFromCoordinates() to locationFromAddress() because convert the address from user input field then change to get the long and lat. Please help me thenks!


Solution

  • You can do both from address to coordinates and vice versa.(with older flutter version & without null safety you can use this)

    1st way using geocoding

    Future<void> getGeoCoderData() async {
        List<Location> locations =
            await locationFromAddress("Gronausestraat 710, Enschede");
        debugPrint("Address to Lat long ${locations.first.latitude} : ${locations.first.longitude}");
    
        List<Placemark> placemarks =
            await placemarkFromCoordinates(52.216653, 6.9462204);
        debugPrint("Lat Long to Address: ${placemarks.first.street} : ${placemarks.first.locality}");
      }
    

    Output: enter image description here

    2nd way using geocoder

    import 'package:geocoder/geocoder.dart';
    
    // From a query / address 
    final query = "1600 Amphiteatre Parkway, Mountain View";
    var addresses = await Geocoder.local.findAddressesFromQuery(query);
    var first = addresses.first;
    print("${first.featureName} : ${first.coordinates}");
    
    // From coordinates to address
    final coordinates = new Coordinates(1.10, 45.50);
    addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
    first = addresses.first;
    print("${first.featureName} : ${first.addressLine}");