How to Make Place Picker on Google Map in Flutter

In this example, we are going to show you how to make a place picker with place search autocomplete and coordinate picker with drag and drop map on Google map in Flutter. See the example below for more details.

Before starting this tutorial, you have to integrate google Maps correctly on your project:

Now, add these packages in your project by adding following lines in pubspec.yaml file:

  1. flutter_google_places_hoc081098
  2. google_maps_webservice
  3. google_api_headers
  4. geocoding
  5. google_maps_flutter 
dependencies:
  flutter:
    sdk: flutter
  flutter_google_places_hoc081098: ^1.0.0-nullsafety.5
  google_api_headers: ^1.1.1
  google_maps_webservice: ^0.0.20-nullsafety.5
  geocoding: ^2.0.1
  google_maps_flutter: ^2.1.1

We had used flutter_google_places package, but it was not working due to version compatibility, so we used the above package instead.

Now, index the asset folder where you have put the coordinate picker image like below on pubspce.yaml file:

flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
     - assets/images/

Activate these APIs on Google Map Console:

Now, see the example below for full Place picker from Google Map in Flutter App.

import 'package:flutter/material.dart';
import 'package:flutter_google_places_hoc081098/flutter_google_places_hoc081098.dart';
import 'package:geocoding/geocoding.dart';
import 'package:google_api_headers/google_api_headers.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_webservice/places.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
   String googleApikey = "GOOGLE_MAP_API_KEY";
  GoogleMapController? mapController; //contrller for Google map
  CameraPosition? cameraPosition;
  LatLng startLocation = LatLng(27.6602292, 85.308027); 
  String location = "Search Location"; 

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
          appBar: AppBar( 
             title: Text("Place Picker in Google Map"),
             backgroundColor: Colors.deepPurpleAccent,
          ),
          body: Stack(
            children:[

              GoogleMap( //Map widget from google_maps_flutter package
                  zoomGesturesEnabled: true, //enable Zoom in, out on map
                  initialCameraPosition: CameraPosition( //innital position in map
                    target: startLocation, //initial position
                    zoom: 14.0, //initial zoom level
                  ),
                  mapType: MapType.normal, //map type
                  onMapCreated: (controller) { //method called when map is created
                    setState(() {
                      mapController = controller; 
                    });
                  },
                  onCameraMove: (CameraPosition cameraPositiona) {
                      cameraPosition = cameraPositiona;
                  },
                  onCameraIdle: () async {
                     List<Placemark> placemarks = await placemarkFromCoordinates(cameraPosition!.target.latitude, cameraPosition!.target.longitude);
                     setState(() {
                        location = placemarks.first.administrativeArea.toString() + ", " +  placemarks.first.street.toString();
                     });
                  },
             ),

             Center( //picker image on google map
                child: Image.asset("assets/images/picker.png", width: 80,),
             ),

             //search autoconplete input
             Positioned(  //search input bar
               top:10,
               child: InkWell(
                 onTap: () async {
                  var place = await PlacesAutocomplete.show(
                          context: context,
                          apiKey: googleApikey,
                          mode: Mode.overlay,
                          types: [],
                          strictbounds: false,
                          components: [Component(Component.country, 'np')],
                                      //google_map_webservice package
                          onError: (err){
                             print(err);
                          }
                      );

                   if(place != null){
                        setState(() {
                          location = place.description.toString();
                        });
                       //form google_maps_webservice package
                       final plist = GoogleMapsPlaces(apiKey:googleApikey,
                              apiHeaders: await GoogleApiHeaders().getHeaders(),
                                        //from google_api_headers package
                        );
                        String placeid = place.placeId ?? "0";
                        final detail = await plist.getDetailsByPlaceId(placeid);
                        final geometry = detail.result.geometry!;
                        final lat = geometry.location.lat;
                        final lang = geometry.location.lng;
                        var newlatlang = LatLng(lat, lang);

                        //move map camera to selected place with animation
                        mapController?.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target: newlatlang, zoom: 17)));
                   }
                 },
                 child:Padding(
                   padding: EdgeInsets.all(15),
                    child: Card(
                       child: Container(
                         padding: EdgeInsets.all(0),
                         width: MediaQuery.of(context).size.width - 40,
                         child: ListTile(
                            leading: Image.asset("assets/images/picker.png", width: 25,),
                            title:Text(location, style: TextStyle(fontSize: 18),),
                            trailing: Icon(Icons.search),
                            dense: true,
                         )
                       ),
                    ),
                 )
               )
             )


            ]
          )
       );
  }
}

In this example, you can search places with places search autocomplete or select palace with drag and drop marker coordinates picker on Google map.

Places search autocomplete

Place picker with Marker

In this way, you can make a places picker with palace search autocomplete, or with drag and drop coordinates picker from Google Map in Flutter app.

No any Comments on this Article


Please Wait...