Open In App

How to Get Address From Coordinates in Flutter?

Improve
Improve
Like Article
Like
Save
Share
Report

Google Maps is of the most used application nowadays for navigation. Sometimes we don’t know the actual address so we search the location from coordinates such as Longitude and Latitude. In this article, we are going to see how to get the actual Address of the Actual location by passing the coordinates in Flutter.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Generating API Key for Using Google Maps

Check out the below article on How to generate an API key for using Google Maps. After developing that key we have to use it within our project to integrate Google Maps. 

Now, follow the Steps to Implement Google Maps in the Flutter Application

Step 3: Adding Dependency to pubspec.yaml File

dependencies:
    flutter: 
    google_maps_flutter: ^2.1.8

Now click on pub.get to configure.

Step 4: Update build.gradle File

Navigate to android>app>build.gradle file and update code on below line. 

Change Compile SDK Version

android {
    compileSdkVersion 31

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

Change Min SDK Version

defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.google_maps"
    minSdkVersion 20
    targetSdkVersion 30
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

Step 5: Add API Key to Android Manifest File

Navigate to android > app > src > main > AndrodManifest.xml file and add the below code in the manifest tag. Make sure to add your Google Maps API key in the value. 

<meta-data android:name="com.google.android.geo.API_KEY"
        android:value="Enter your API key here"/>

Step 6: Working with main.dart File

Navigate to lib > main.dart file and add the below code to it. Comments are added in the code to get to know in detail. 

Dart




import 'package:flutter/material.dart';
import 'package:google_maps/Convert_Lat_Long.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // on below line we are specifying title of our app
      title: 'GFG',
      // on below line we are hiding debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // on below line we are specifying theme
        primarySwatch: Colors.green,
      ),
      // First screen of our app
      home: const Convert_Lat_Long(),
    );
  }
}


Step 7: Creating a new Dart File for Convert_Lat_Long File

Navigate to lib > Right click on it > New > Dart File and name it as Convert_Lat_Long.dart. After creating that file add the below code to it. Comments are added in the code to get to know in detail.

Dart




import 'package:flutter/material.dart';
import 'package:flutter_geocoder/geocoder.dart';
 
class Convert_Lat_Long extends StatefulWidget {
  const Convert_Lat_Long({Key? key}) : super(key: key);
  @override
  _Convert_Lat_LongState createState() => _Convert_Lat_LongState();
}
 
class _Convert_Lat_LongState extends State<Convert_Lat_Long> {
  // on below line we have created controllers for accessing values from textfield
  TextEditingController latitudeController = new TextEditingController();
  TextEditingController longitudeController = new TextEditingController();
  // variable created to store the address
  String stAddress = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // on below line we have given title of App
        title: Text('GFG'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text('Get Address from Coordinates', style: TextStyle(color: Color(0xFF0F9D58), fontWeight: FontWeight.bold, fontSize: 20),),
              SizedBox(height: 10),
 
              // textfield1 for taking input as latitude
              TextField(
                controller: latitudeController,
                decoration: InputDecoration(
                    // Given Hint Text
                    hintText: 'Latitude',
                    border: OutlineInputBorder(
                      // Given border to textfield
                      borderRadius: BorderRadius.circular(10),
                    )
                ),
              ),
              SizedBox(height: 10),
 
              // textfield2 for taking input as longitude
              TextField(
                controller: longitudeController,
                decoration: InputDecoration(
                    // Given hint text
                    hintText: 'Longitude',
                    border: OutlineInputBorder(
                      // given border to textfield
                      borderRadius: BorderRadius.circular(10),
                    )
                ),
              ),
              SizedBox(height: 10),
               
              // Given padding to the Container
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Container(
                    child: Center(child: Text(stAddress),),
                ),
              ),
               SizedBox(height: 10),
 
              GestureDetector(
                onTap: () async {
                   
                  // stored the value of latitude in lat from textfield
                  String lat = latitudeController.text;
                  // stored the value of longitude in lon from textfield
                  String lon = longitudeController.text;
 
                  // converted the lat from string to double
                  double lat_data = double.parse(lat);
                  // converted the lon from string to double
                  double lon_data = double.parse(lon);
 
                  // Passed the coordinates of latitude and longitude
                  final coordinates = new Coordinates(lat_data, lon_data);
                  var address = await Geocoder.local.findAddressesFromCoordinates(coordinates);
                  var first = address.first;
 
                  // on below line we have set the address to string
                  setState(() {
                    stAddress = first.addressLine.toString();
                  });
 
                },
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(
                    decoration: BoxDecoration(
                      // specified color for button
                      color: Colors.green,
                    ),
                    // given height for button
                    height: 50,
                    child: Center(
                      // on below line we have given button name
                      child: Text('Convert',style: TextStyle(color: Colors.white),),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Output:



Last Updated : 22 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads