Flutter Google Map Search Location | Auto Complete Address | TypeAheadField

3 min read 2 hours ago
Published on Oct 14, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, you will learn how to implement an address search feature in a Flutter application using Google Maps. We will utilize the flutter_typeahead package to enable auto-complete functionality for addresses. This feature enhances user experience by suggesting locations as users type, making it easier and quicker to find the desired address.

Step 1: Set Up Your Flutter Project

To begin, ensure you have Flutter installed on your machine. If you don't have a project yet, create one.

  1. Create a new Flutter project:

    flutter create google_map_search
    
  2. Navigate to your project directory:

    cd google_map_search
    
  3. Open the project in your preferred IDE.

Step 2: Add Required Dependencies

You need to include several packages in your pubspec.yaml file to enable Google Maps and address auto-completion.

  1. Open pubspec.yaml.

  2. Add the following dependencies:

    dependencies:
      flutter:
        sdk: flutter
      google_maps_flutter: ^2.0.1
      flutter_typeahead: ^3.1.3
      http: ^0.13.3
    
  3. Run the command to install the dependencies:

    flutter pub get
    

Step 3: Obtain Google Maps API Key

To use Google Maps and Places API, you will need an API key.

  1. Go to the Google Cloud Console.
  2. Create a new project.
  3. Enable the following APIs for your project:
    • Maps SDK for Android
    • Places API
  4. Create credentials to obtain your API key.
  5. Restrict your API key to prevent unauthorized use.

Step 4: Configure Android and iOS Settings

Make sure to configure your application for both Android and iOS platforms.

For Android:

  1. Open android/app/src/main/AndroidManifest.xml.
  2. Add your API key within the <application> tag:
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="YOUR_API_KEY"/>
    

For iOS:

  1. Open ios/Runner/Info.plist.
  2. Add your API key:
    <key>GMSApiKey</key>
    <string>YOUR_API_KEY</string>
    

Step 5: Implement the Search Functionality

Now, let's create the UI and implement the logic for the address search.

  1. Create a new Dart file for the search widget:

    • For example, create search_widget.dart.
  2. Import necessary packages:

    import 'package:flutter/material.dart';
    import 'package:flutter_typeahead/flutter_typeahead.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
  3. Create the TypeAheadField:

    class SearchWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return TypeAheadField(
          textFieldConfiguration: TextFieldConfiguration(
            decoration: InputDecoration(labelText: 'Search Address'),
          ),
          suggestionsCallback: (pattern) async {
            return await getSuggestions(pattern);
          },
          itemBuilder: (context, suggestion) {
            return ListTile(
              title: Text(suggestion['description']),
            );
          },
          onSuggestionSelected: (suggestion) {
            // Navigate to map or display selected address
          },
        );
      }
    
      Future<List<dynamic>> getSuggestions(String query) async {
        final response = await http.get(
          Uri.parse(
            'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$query&key=YOUR_API_KEY',
          ),
        );
        return json.decode(response.body)['predictions'];
      }
    }
    

Step 6: Integrate the Widget into Your App

Include your SearchWidget in your main application screen.

  1. Open lib/main.dart.

  2. Update the build method:

    import 'search_widget.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(title: Text('Google Map Search')),
            body: SearchWidget(),
          ),
        );
      }
    }
    

Conclusion

You have successfully implemented a Google Maps address search feature with auto-complete in your Flutter app. Users can now type in addresses and receive suggestions, enhancing the overall user experience.

Next Steps

  • Explore additional features such as displaying the selected location on the map.
  • Consider adding error handling for network requests.
  • Experiment with customizing the UI to match your app's design.

By following this guide, you can create a more interactive and user-friendly application. Happy coding!