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

42,273

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
Share:
42,273

Related videos on Youtube

Guilherme Oliveira
Author by

Guilherme Oliveira

Trying to find a good coding tattoo.

Updated on December 15, 2021

Comments

  • Guilherme Oliveira
    Guilherme Oliveira over 2 years

    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

  • Guilherme Oliveira
    Guilherme Oliveira about 5 years
    Hi, @DK15. Thank you. Do you know any tutorial showing how to implement that? I'm a beginner yet.
  • Darshan
    Darshan about 5 years
    I updated my answer with working code sample. Hope this answers your question.
  • Guilherme Oliveira
    Guilherme Oliveira almost 5 years
    Hi, DK15! Thank you. The code is working with my API Key. I would like to put the results returned from PlacesAutocomplete to a custom listview. So I would like to store it on a List variable and print it. Is that possible to do? Thanks again!
  • Darshan
    Darshan almost 5 years
    Yes, you can make use of placeId to get id of the location you selected and its corresponding address to store in custom listview and can access it using the variable you declare for listview.
  • Darshan
    Darshan almost 5 years
    Also, if your original question has been answered, you can accept my answer and upvote it so it would be helpful for others to know as well :-)
  • Guilherme Oliveira
    Guilherme Oliveira almost 5 years
    Sure! Thank you again!
  • Leoog
    Leoog almost 5 years
    You did all the work for us. Thanks it works perfectly.
  • sainu
    sainu over 4 years
    @DK15 can you please show the import statement because I import flutter_google_places as import 'package:flutter_google_places/flutter_google_places.dart'; and I got the error for GoogleMapsPlaces as undefined class.
  • Noam
    Noam over 4 years
    @DK15 you should add a token id to your show() call and use the same token in your place details request. otherwise, you'll be charged on each request separately.
  • David Mulder
    David Mulder over 4 years
    @sainu import 'package:google_maps_webservice/places.dart'; ended up working
  • BIS Tech
    BIS Tech over 4 years
    how to implement without open another screen?
  • Admin
    Admin about 4 years
    @BloodLoss mode: Mode.overlay
  • Monis
    Monis about 4 years
    import 'package:flutter_google_places/flutter_google_places.dart'; import 'package:google_maps_webservice/places.dart';
  • Goutam B Seervi
    Goutam B Seervi over 3 years
    I want to be able to use gps as the current location how can I do that in the same view?
  • genericUser
    genericUser almost 3 years
    The Api_key is google cloud platform Places API key. developers.google.com/maps/documentation/places/web-service/‌​…
  • genericUser
    genericUser almost 3 years
    What is Prediction? Please provide your imports with your example