searchflutterautocompletemapsgoogle-places-autocomplete

How to create a simple google maps address search with autocomplete in flutter and get latitude and longitude?


I'm new at Flutter and I'm trying to build a simple google maps app. I've already implemented google maps to the app and it is running perfect.

But now I want to add google maps autocomplete and I can't find a simple tutorial or example that is focused on it.

I have a TextField and I want to show places and addresses below it according to what the user types.

After showing the results, I need to get its latitude and longitude to mark on the map. The code below represents my BottomSheet, that contains my TexField and need to implement some list below it after some written text.

void _settingModalBottomSheet(context) {
    double statusBarHeight = MediaQuery.of(context).padding.top;

    showModalBottomSheet(
      context: context,
      builder: (builder) {
        return Container(
          padding: EdgeInsets.only(top: statusBarHeight),
          color: Colors.transparent,
          child: Container(
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              color: Colors.blueAccent,
              borderRadius: BorderRadius.only(
                topLeft: const Radius.circular(10.0), topRight: const Radius.circular(10.0))),
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
                    child: Container(
                      height: 50.0,
                      width: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10.0),
                        color: Colors.white
                      ),
                      child: TextField(
                        textInputAction: TextInputAction.search,
                        decoration: InputDecoration(
                          hintText: "Para onde vamos?",
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.only(left: 15.0, top: 15.0),
                          suffixIcon: IconButton(
                            icon: Icon(Icons.search),
                            onPressed: searchAndNavigate,
                            iconSize: 30.0,
                          )
                        ),
                        onChanged: (val) {
                          setState(() {
                            searchAddr = val;
                          }
                        );
                      },
                      onSubmitted: (term) {
                        searchAndNavigate();
                      },
                    ),
                  ),
                ),
              ],
            )
          ),
        );
      }
    );
  }

Current screen


Solution

  • You can use flutter_google_places plugin which shows the places in the autocomplete list as you type it and also returns lat and long of the place/address selected.

    ===== Working code =======

    1. Add flutter_google_places plugin and import it in your dart file.
    2. Add geo_coder plugin and import it in same dart file. (Required to access geocoding services)
    3. Generate google api key for your project.

    main.dart:

    void main() => runApp(MyApp());
    
    const kGoogleApiKey = "Api_key";
    
    GoogleMapsPlaces _places = GoogleMapsPlaces(apiKey: kGoogleApiKey);
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: demo(),
          ),
        );
      }
    }
    
    class demo extends StatefulWidget {
      @override
      demoState createState() => new demoState();
    }
    
    class demoState extends State<demo> {
      @override
      Widget build(BuildContext context) {
        
        return Scaffold(
          body: Container(
            alignment: Alignment.center,
            child: RaisedButton(
              onPressed: () async {
                // show input autocomplete with selected mode
                // then get the Prediction selected
                Prediction p = await PlacesAutocomplete.show(
                    context: context, apiKey: kGoogleApiKey);
                displayPrediction(p);
              },
              child: Text('Find address'),
    
            )
          )
        );
      }
    
      Future<Null> displayPrediction(Prediction p) async {
        if (p != null) {
          PlacesDetailsResponse detail =
          await _places.getDetailsByPlaceId(p.placeId);
    
          var placeId = p.placeId;
          double lat = detail.result.geometry.location.lat;
          double lng = detail.result.geometry.location.lng;
    
          var address = await Geocoder.local.findAddressesFromQuery(p.description);
    
          print(lat);
          print(lng);
        }
      }
    }
    

    Result:

    When you tap on Find Address button, it opens new screen with built-in search app bar in which you can type address / place you are looking for which shows corresponding results in autocomplete list and prints lat and long of the place you selected.

    enter image description here

    lat: 52.3679843
    lng: 4.9035614