Place picker for Flutter using open street, Here maps and google map

Overview

Flutter Place Picker

A Flutter plugin which provides 'Picking Place' using Open Street, Here Maps and Google Maps widget.

Much thanks to Terry Kwon

The project relies on below packages.

Map using Flutter's official google_maps_flutter
Fetching current location using Baseflow's geolocator
Place and Geocoding API using hadrienlejard's google_maps_webservice
Builder using kevmoo's tuple

The package comes along with Laravel(PHP Framework) server which you can host for on your own. Link to serve repository here...

Preview

Support

If the package was useful or saved your time, please do not hesitate to buy me a cup of coffee! ;)
The more caffeine I get, the more useful projects I can make in the future.

Buy Me A Coffee

Getting Started

  • Get an API key at https://cloud.google.com/maps-platform/.

  • Enable Google Map SDK for each platform.

    • Go to Google Developers Console.
    • Choose the project that you want to enable Google Maps on.
    • Select the navigation menu and then select "Google Maps".
    • Select "APIs" under the Google Maps menu.
    • To enable Google Maps for Android, select "Maps SDK for Android" in the "Additional APIs" section, then select "ENABLE".
    • To enable Google Maps for iOS, select "Maps SDK for iOS" in the "Additional APIs" section, then select "ENABLE".
    • Make sure the APIs you enabled are under the "Enabled APIs" section.
  • You can also find detailed steps to get started with Google Maps Platform here.

Android

Specify your API key in the application manifest android/app/src/main/AndroidManifest.xml:

<manifest ...
  <application ...
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/>

NOTE: As of version 3.0.0 the geolocator plugin switched to the AndroidX version of the Android Support Libraries. This means you need to make sure your Android project is also upgraded to support AndroidX. Detailed instructions can be found here.

The TL;DR version is:

  1. Add the following to your "gradle.properties" file:
android.useAndroidX=true
android.enableJetifier=true
  1. Make sure you set the compileSdkVersion in your "android/app/build.gradle" file to 28:
android {
 compileSdkVersion 28

 ...
}
  1. Make sure you replace all the android. dependencies to their AndroidX counterparts (a full list can be found here: https://developer.android.com/jetpack/androidx/migrate).

iOS

Specify your API key in the application delegate ios/Runner/AppDelegate.m:

#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GMSServices provideAPIKey:@"YOUR KEY HERE"];
  [GeneratedPluginRegistrant registerWithRegistry:self];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

Or in your swift code, specify your API key in the application delegate ios/Runner/AppDelegate.swift:

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

On iOS you'll need to add the following entries to your Info.plist file (located under ios/Runner) in order to access the device's location.

Simply open your Info.plist file and add the following:

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to location when open and in the background.</string>

In addition, you need to add the Background Modes capability to your XCode project (Project > Signing and Capabilties > "+ Capability" button) and select Location Updates.g>This app needs access to location when open and in the background.

Opt-in to the embedded views preview by adding a boolean property to the app's Info.plist file with the key io.flutter.embedded_views_preview and the value YES.

<key>io.flutter.embedded_views_preview</key>
<true/>

Usage

Basic usage

You can use PlacePicker by pushing to a new page using Navigator, OR put as a child of any widget.
When the user picks a place on the map, it will return result to 'onPlacePicked' with PickResult type. Alternatively, you can build your own way with 'selectedPlaceWidgetBuilder' and fetch result from it (See the instruction below).

Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => FlutterPlacePicker(
          apiKey: APIKeys.apiKey,   // Put YOUR OWN KEY here.
          onPlacePicked: (result) { 
            Navigator.of(context).pop();
          },
          initialPosition: HomePage.kInitialPosition,
          useCurrentLocation: true,
        ),
      ),
    );

PickResult

Parameter Type Description
placeId String A textual identifier that uniquely identifies a place. To retrieve information about the place, pass this identifier in the placeId field of a Places API request. See PlaceId for more information.
geometry Geometry Contains geometry information about the result, generally including the location (geocode) of the place and (optionally) the viewport identifying its general area of coverage.
formattedAddress String A string containing the human-readable address of this place. Often this address is equivalent to the "postal address".
types List<String> Contains an array of feature types describing the given result. See the list of supported types. XML responses include multiple elements if more than one type is assigned to the result.
addressComponents List<AddressComponent> An array containing the separate components applicable to this address.

** Below results will be fetched only when using auto-complete search or usePlaceDetailSearch is set to true when searching by dragging the map.

PickResult (Optional)

Parameter Type Description
adrAddress String A representation of the place's address in the adr microformat
formattedPhoneNumber String Contains the place's phone number in its local format
id String ? (Not documented at Google - see more info below)
reference String ? (Not documented at Google - see more info below)
icon String The URL of a suggested icon which may be displayed to the user when indicating this result on a map.
name String Human-readable name for the returned result
openingHours OpeningHoursDetail Opening hour information
photos List<Photo> Array of photo objects, each containing a reference to an image
internationalPhoneNumber String The place's phone number in international format
priceLevel PriceLevel The price level of the place, on a scale of 0 to 4. The exact amount indicated by a specific value will vary from region to region.
rating num The place's rating, from 1.0 to 5.0, based on aggregated user reviews.
scope String
url String The URL of the official Google page for this place.
vicinity String Lists a simplified address for the place, including the street name, street number, and locality, but not the province/state, postal code, or country
utcOffset num The number of minutes this place’s current timezone is offset from UTC
website String The authoritative website for this place
reviews List<Review> JSON array of up to five reviews

More info about results at Google document.

PlacePicker

Parameter Type Description
apiKey String (Required) Your google map API Key
serverUrl String Your host server url (eg. https://www.your-server.com/api/). Null or empty serverUrl uses our fallback Url (phplaravel-641695-2829489.cloudwaysapps.com/api/)
onPlacePicked Callback(PickResult) Invoked when user picks the place and selects to use it. This will not be called if you manually build 'selectedPlaceWidgetBuilder' as you will override default 'Select here' button.
initialPosition LatLng (Required) Initial center position of google map when it is created. If useCurrentLocation is set to true, it will try to get device's current location first using GeoLocator.
useCurrentLocation bool Whether to use device's current location for initial center position. This will be used instead of initial position when it is set to true AND user ALLOW to collect their location. If DENIED, initialPosition will be used.
desiredLocationAccuracy LocationAccuracy Accuracy of fetching current location. Defaults to 'high'.
hintText String Hint text of search bar
searchingText String A text which appears when searching is performing. Default to 'Searching...'
proxyBaseUrl String Used for API calling on google maps. In case of using a proxy the baseUrl can be set. The apiKey is not required in case the proxy sets it.
httpClient Client Used for API calling on google maps. In case of using a proxy url that requires authentication or custom configuration.
autoCompleteDebounceInMilliseconds int Debounce timer for auto complete input. Default to 500
cameraMoveDebounceInMilliseconds int Debounce timer for searching place with camera(map) dragging. Defaults to 750
intialMapType MapType MapTypes of google map. Defaults to normal.
enableMapTypeButton bool Whether to display MapType change button on the map
enableMyLocationButton bool Whether to display my location button on the map
usePinPointingSearch bool Defaults to true. This will allow user to drag map and get a place info where the pin is pointing.
usePlaceDetailSearch bool Defaults to false. Setting this to true will get detailed result from searching by dragging the map, but will use +1 request on Place Detail API.
onAutoCompleteFailed Callback(String) Invoked when auto complete search is failed
onGeocodingSearchFailed Callback(String) Invoked when searching place by dragging the map failed
onMapCreated MapCreatedCallback Returns google map controller when created
selectedPlaceWidgetBuilder WidgetBuilder Specified on below section
pinBuilder WidgetBuilder Specified on below section
autocompleteOffset num The position, in the input term, of the last character that the service uses to match predictions
autocompleteRadius num The distance (in meters) within which to return place results
autocompleteLanguage String The language code, indicating in which language the results should be returned, if possible.
autocompleteComponents List<Components> A grouping of places to which you would like to restrict your results. Currently, you can use components to filter by up to 5 countries.
autocompleteTypes List<String> The types of place results to return. See Place Types.
strictBounds bool Returns only those places that are strictly within the region defined by location and radius.
region String region — The region code, specified as a ccTLD (country code top-level domain) two-character value. Most ccTLD codes are identical to ISO 3166-1 codes, with some exceptions. This parameter will only influence, not fully restrict, search results. If more relevant results exist outside of the specified region, they may be included. When this parameter is used, the country name is omitted from the resulting formatted_address for results in the specified region.
selectInitialPosition bool Whether to display selected place on initial map load. Defaults to false.
resizeToAvoidBottomInset bool Refer to Scaffold's resizeToAvoidBottomInset property.
initialSearchString String Sets initial search string for auto complete search
searchForInitialValue bool Wether to automatically search for initial value on start
forceAndroidLocationManager bool On Android devices you can set this to true to force the geolocator plugin to use the 'LocationManager' to determine the position instead of the 'FusedLocationProviderClient'. On iOS this is ignored.
myLocationButtonCooldown int Cooldown time in seconds for the 'myLocationButton'. Defaults to 10 seconds.
forceSearchOnZoomChanged bool Wether to allow place search even when the zoom has changed. Defaults to false.
automaticallyImplyAppBarLeading bool By default, there is a back button on the top. Setting false will remove the back button.
autocompleteOnTrailingWhitespace bool Whether to allow autocomplete to run even on whitespace at the end of the search. Defaults to false. Issue ref #54.

More info about autocomplete search at Google document.

Customizing picked place visualisation

By default, when a user picks a place by using auto complete search or dragging the map, we display the information at the bottom of the screen (FloatingCard).

However, if you don't like this UI/UX, simply override the builder using 'selectedPlaceWidgetBuilder'. FlocatingCard widget can be reused which is floating around the screen or build an entirely new widget as you want. It is stacked with the map, so you might want to use the Positioned widget.

Note that using this customization WILL NOT INVOKE [onPlacePicked] callback as it will override default 'Select here' button on floating card

...
PlacePicker(apiKey: APIKeys.apiKey,
            ...
            selectedPlaceWidgetBuilder: (_, selectedPlace, state, isSearchBarFocused) {
              return isSearchBarFocused
                  ? Container()
                  // Use FloatingCard or just create your own Widget.
                  : FloatingCard(
                      bottomPosition: 0.0,    // MediaQuery.of(context) will cause rebuild. See MediaQuery document for the information.
                      leftPosition: 0.0,
                      rightPosition: 0.0,
                      width: 500,
                      borderRadius: BorderRadius.circular(12.0),
                      child: state == SearchingState.Searching ? 
                                      Center(child: CircularProgressIndicator()) : 
                                      RaisedButton(onPressed: () { print("do something with [selectedPlace] data"); },),
                   );
            },
            ...
          ),
...
Parameters Type Description
context BuildContext Flutter's build context value
selectedPlace PickResult Result data of user selected place
state SearchingState State of searching action. (Idle, Searching)
isSearchBarFocused bool Whether the search bar is currently focused so the keyboard is shown

Customizing Pin

By default, Pin icon is provided with very simple picking animation when moving around.
However, you can also create your own pin widget using 'pinBuilder'

FlutterPlacePicker(apiKey: APIKeys.apiKey,
            ...
            pinBuilder: (context, state) {
                  if (state == PinState.Idle) {
                    return Icon(Icons.favorite_border);
                  } else {
                    return AnimatedIcon(.....);
                  }
                },
            ...                        
          ),
...
Parameters Type Description
context BuildContext Flutter's build context value
state PinState State of pin. (Preparing; When map loading, Idle, Dragging)

Changing Colours of default FloatingCard

While you can build your own prediction tile, you still can change the style of default tile using themeData as below:

// Light Theme
final ThemeData lightTheme = ThemeData.light().copyWith(
  // Background color of the FloatingCard
  cardColor: Colors.white,
  buttonTheme: ButtonThemeData(
    // Select here's button color
    buttonColor: Colors.black,
    textTheme: ButtonTextTheme.primary,
  ),
);

// Dark Theme
final ThemeData darkTheme = ThemeData.dark().copyWith(
  // Background color of the FloatingCard
  cardColor: Colors.grey,
  buttonTheme: ButtonThemeData(
    // Select here's button color
    buttonColor: Colors.yellow,
    textTheme: ButtonTextTheme.primary,
  ),
);

Feature Requests and Issues

Please file feature requests and bugs at the issue tracker.

Buy Me A Coffee

Connect with me

Sam | Twitter Sam | LinkedIn Sam | Instagram

Visitors Count

Loading

You might also like...

Nepali date picker - Material Style Date Picker with Bikram Sambat(Nepali) Calendar Support

Nepali date picker - Material Style Date Picker with Bikram Sambat(Nepali) Calendar Support

Nepali Date Picker + Calendar Material and Cupertino Styled Date Picker, Date Range Picker and Calendar with Bikram Sambat(Nepali) Support. Nepali Dat

Jan 3, 2023

Maps for Flutter developers. Supports Apple, Bing, and Google APIs.

Overview Cross-platform geographic maps for Flutter applications. Pull requests are welcome! The packages are licensed under the Apache License 2.0. P

Oct 13, 2022

FormField to pick one or more locations from open streat map

FormField to pick one or more locations from open streat map Features Pick single location Pick multi locations display open street maps can work with

Dec 15, 2022

Deliverzler - Delivery App for Restaurants built on Flutter with Firebase, Google Maps, Local Notifications, FCM Notifications

Deliverzler - Delivery App for Restaurants built on Flutter with Firebase, Google Maps, Local Notifications, FCM Notifications

Deliverzler A new open source Delivery App for Restaurants created using Flutter

Jan 7, 2023

The purpose of this project was to test Google Map Services in connection with Flutter on Android, iOS

The purpose of this project was to test Google Map Services in connection with Flutter on Android, iOS

A large variety of apps depend on map services. The purpose of this project was to test Google Map Services in connection with Flutter on Android, iOS and Web platforms. Here is what I got:

Oct 17, 2022

Use Flutter_web 💪 to implement the UI challenge of Google Maps on uplabs .

Use Flutter_web 💪 to implement the UI challenge of Google Maps on uplabs .

flutter_web_challenge_googlemaps_web Use Flutter_web 💪 to implement the UI challenge of Google Maps on uplabs . 中文版本 Designer : Joydeep Sengupta Upla

Oct 31, 2022

dynamic link , notifaction , google map, animated-to

dynamicapp A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get you started i

Dec 29, 2021

A flutter package from AsurRaa for widgets and utility functions to support mobile departments here.

A flutter package from AsurRaa for widgets and utility functions to support mobile departments here.

sura_flutter A flutter package from AsurRaa for custom widgets and utility functions. Migrate from 0.2.x to 0.3.x BREAKING CHANGE: remove FutureManage

Nov 15, 2022
Releases(v0.0.1-dev.4)
  • v0.0.1-dev.4(Sep 2, 2022)

Owner
Samuel Annin Yeboah
Loves Music
Samuel Annin Yeboah
Note the place to remember it's name and descriptions along with google map location.

Note the Place Note the place to remember it's name and descriptions along with map location. View in Web Click here for web view Note: for bettter lo

subash kc 4 May 5, 2022
LakhanKumawat ᵖ⁺ 12 Dec 6, 2022
Wall-street-news - News App work with HttpClient in Flutter

Flutter News App Demo This project is to showcase how to work with HttpClient in

Trần Văn Nguyên 6 Oct 16, 2022
Color picker for Flutter, based on the Google Docs color picker.

Material ColorPicker Color picker for Flutter, based on the Google Docs color picker. Getting Started You can embed into your material app or use it o

Razvan Lung 103 Oct 30, 2022
All of my open source flutter and dart projects, tutorials are published here.

Flutter In this repository I publish all of my open source flutter, dart projects, and tutorials. Written Tutorials Dart Programming Language for Prog

Mahmud Ahsan 143 Jan 1, 2023
Map location picker for flutter Based on google_maps_flutter

map_location_picker: A simple library to pick a location on a map. Made by Arvind @rvndsngwn: Compatibility with Geolocator Use of Google map APIs Add

Arvind Sangwan 9 Nov 27, 2022
Complete Implementation of Google maps in Flutter using Riverpod

Complete Implementation of Google maps in Flutter using Riverpod (Google Maps ft. Auto Suggestions, GPS tracking, Nearby places, polylines, directions, Review, Contact Details & Photos of a place and much more..)

Akash Mishra 10 Dec 31, 2022
A flutter date time picker inspired by flutter-cupertino-date-picker

Flutter Datetime Picker (Pub) flutter_datetime_picker A flutter date time picker inspired by flutter-cupertino-date-picker you can choose date / time

null 0 Nov 30, 2021
A note-taking app powered by Google services such as Google Sign In, Google Drive, and Firebase ML Vision.

Smart Notes A note-taking app powered by Google services such as Google Sign In, Google Drive, and Firebase ML Vision. This is an official entry to Fl

Cross Solutions 88 Oct 26, 2022
Form builder image picker - Form builder image picker for flutter

form_builder_image_picker Field for picking image(s) from Gallery or Camera for

Ferri Sutanto 0 Jan 28, 2022