flutterdartgeolocationgeocodinggeocoder

How to convert LatLng to address Flutter (both iOS and Android version)


I am creating an app with Flutter that uses geocoding plugin in order to convert LatLng position to address.

Here my code:

import 'package:geocoding/geocoding.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  late String location = "location name";

  Future<String> getAddress() async {
    List<Placemark> placemarks = await placemarkFromCoordinates(
        45.478981,9.207120,
        localeIdentifier: 'it_It');
    return placemarks[0].name.toString();
  }

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("Convert LatLng to Address")),
        body: Center(
          child: Stack(children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(location),
                ElevatedButton(
                  onPressed: () {
                    getAddress().then((value) => {
                          setState(() {
                            location = value;
                          }),
                          print(value)
                        });
                  },
                  child: const Text('Convert LatLng'),
                ),
              ],
            ),
          ]),
        ));
  }
}

The result of the conversion is different between iOS and Android version, for example:

LatLng = 45.478981,9.207120

iOS version result: "Via Alessandro Tadino 21"

Android version result: "46"

I don't understand why it is different, should I use another plugin? Perhaps the plugin uses two different technologies for iOS and Android. Does Android use a sort of Google Maps plugin?


Solution

  • What you need is reverse geocoding

    Reverse geocoding is the process of converting geographic coordinates into a human-readable address.

    Since you need exact same outputs on both android and iOS devices, I'd suggest you use Google Geocoding API

    Then you can use the API key with google_geocoding package and get places using coordinates

    var googleGeocoding = GoogleGeocoding("API-KEY");
    var result = await googleGeocoding.geocoding.getReverse(LatLon(40.714224,-73.961452));