Flutter Google Places Autocomplete Widgets

Overview

Build Status codecov Star on Github Buy Me A Coffee

google_maps_webservice

General Information

This is the Dart Library for Google Maps Webservices. You can find the Google Maps Platform Documentation here, but if you're new to this, you may want to start here.

API Key

To use this library you need a Web API key. Follow these steps to acquire the key relevant to your particular Dart application.

These keys are not to be used individually as Android or iOS API keys, but they are instead meant to be used in your Dart application.

Availables API

Usage

Geocoding

import "package:google_maps_webservice/geocoding.dart";

final geocoding = GoogleMapsGeocoding(apiKey: "<API_KEY>");
final geocoding = GoogleMapsGeocoding(apiKey: "<API_KEY>", httpClient: BrowserClient());
final geocoding = GoogleMapsGeocoding(baseUrl: "http://myProxy.com");

GeocodingResponse response = await geocoding.searchByAddress("1600 Amphitheatre Parkway, Mountain View, CA");

Places

import "package:google_maps_webservice/places.dart";

final places = GoogleMapsPlaces(apiKey: "<API_KEY>");
final places = GoogleMapsPlaces(apiKey: "<API_KEY>", httpClient: BrowserClient());
final places = GoogleMapsPlaces(baseUrl: "http://myProxy.com");

PlacesSearchResponse response = await places.searchNearbyWithRadius(Location(lat: 31.0424, lng: 42.421), 500);
PlacesSearchResponse response = await places.searchNearbyWithRankby(Location(lat: 31.0424, lng: 42.421), "distance");
PlacesSearchResponse response = await places.searchByText("123 Main Street");

PlacesDetailsResponse response = await places.getDetailsByPlaceId("PLACE_ID");
PlacesDetailsResponse response = await places.getDetailsByReference("REF");

Timezone

import "package:google_maps_webservice/timezone.dart";

final timezone = GoogleMapsTimezone(apiKey: "<API_KEY>");
final timezone = GoogleMapsTimezone(apiKey: "<API_KEY>", httpClient: BrowserClient());
final timezone = GoogleMapsTimezone(baseUrl: "http://myProxy.com");

TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421));
TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421), timestamp: DateTime.utc(2019, 4, 24));
TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421), timestamp: DateTime.utc(2019, 4, 24), language: 'es');

Static Map

  StaticMap mapStatic = StaticMap(
    apiKey,
    markers: List.from([
      Location(lat: 23.721160, lng: 90.394435),
      Location(lat: 23.732322, lng: 90.385142),]
    ),
    path: Path(
      enc: 'svh~F`j}uOusC`bD',
      color: 'black',
    ),
    scale: 'false'
  )

  String url = mapStatic.getUrl();

  Image.network(url)

Proxy

In case of using a proxy the baseUrl can be set. The apiKey is not required in case the proxy sets it. (Not storing the apiKey in the app is good practice)

Feature Requests and Issues

Please file feature requests and bugs at the issue tracker.

Comments
  • No 'Access-Control-Allow-Origin' header is present on the requested resource

    No 'Access-Control-Allow-Origin' header is present on the requested resource

    Hello, i am getting this error when i send a request to maps/api/place. I am developing for web. Thanks

    Error: Access to fetch at 'https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJ70taCKKAhYAR5IMmYwQT4Ts&key={APIKEY}' from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

    // dependencies dependencies: flutter: sdk: flutter provider: ^3.1.0 cupertino_icons: ^0.1.3 cloud_firestore: ^0.13.4+2 google_maps_flutter: ^0.5.25+3 google_maps_webservice: ^0.0.16 location: ^2.3.5

    opened by taobad 10
  • add symmetric tests on toJson where we had fromJson

    add symmetric tests on toJson where we had fromJson

    Hi there! I've run into the same problem as here https://github.com/lejard-h/google_maps_webservice/issues/75 and made a quick fix. I tried not to change much code. Please let me know what do you think. Best, Vladimir

    opened by bobagold 7
  • Null safety migration

    Null safety migration

    Dart Null Safety is in beta and packages should start to migrate. Is a null safe pre release already in the works. If not I could offer my help migrating this package.

    opened by DevNico 6
  • Unhandled Exception: Unhandled error type 'Null' is not a subtype of type 'String' calling getDetailsByPlaceId

    Unhandled Exception: Unhandled error type 'Null' is not a subtype of type 'String' calling getDetailsByPlaceId

    Calling getDetailsByPlaceId it throws this: E/flutter ( 7283): #0 _$PlaceDetailsFromJson (package:google_maps_webservice/src/places.g.dart:136:37) E/flutter ( 7283): #1 new PlaceDetails.fromJson (package:google_maps_webservice/src/places.dart:710:7) E/flutter ( 7283): #2 _$PlacesDetailsResponseFromJson (package:google_maps_webservice/src/places.g.dart:294:26) E/flutter ( 7283): #3 new PlacesDetailsResponse.fromJson (package:google_maps_webservice/src/places.dart:838:7) E/flutter ( 7283): #4 GoogleMapsPlaces._decodeDetailsResponse (package:google_maps_webservice/src/places.dart:528:29) E/flutter ( 7283): #5 GoogleMapsPlaces.getDetailsByPlaceId (package:google_maps_webservice/src/places.dart:126:12)

    It seems that adr_address could be null.

    version: 0.0.20-nullsafety.2

    opened by dagix5 5
  • Error: FormatException: SyntaxError: Unexpected token S in JSON at position 0

    Error: FormatException: SyntaxError: Unexpected token S in JSON at position 0

    PlacesSearchResponse response =await places.searchByText("123 Main Street");

    Restarted application in 414ms. Error: FormatException: SyntaxError: Unexpected token S in JSON at position 0 at Object.throw_ [as throw] (http://localhost:11311/dart_sdk.js:5342:11) at Object._parseJson (http://localhost:11311/dart_sdk.js:49743:19) at JsonDecoder.convert (http://localhost:11311/dart_sdk.js:47493:22) at JsonCodec.decode (http://localhost:11311/dart_sdk.js:47190:48) at places.GoogleMapsPlaces.new.[_decodeSearchResponse] (http://localhost:11311/packages/google_maps_webservice/src/places.dart.lib.js:339:76) at places.GoogleMapsPlaces.new.searchByText (http://localhost:11311/packages/google_maps_webservice/src/places.dart.lib.js:176:43) at searchByText.next () at http://localhost:11311/dart_sdk.js:39157:33 at _RootZone.runUnary (http://localhost:11311/dart_sdk.js:39014:58) at _FutureListener.thenAwait.handleValue (http://localhost:11311/dart_sdk.js:34000:29) at handleValueCallback (http://localhost:11311/dart_sdk.js:34560:49) at Function._propagateToListeners (http://localhost:11311/dart_sdk.js:34598:17) at _Future.new.[_completeWithValue] (http://localhost:11311/dart_sdk.js:34440:23) at async._AsyncCallbackEntry.new.callback (http://localhost:11311/dart_sdk.js:34463:35) at Object._microtaskLoop (http://localhost:11311/dart_sdk.js:39301:13) at _startMicrotaskLoop (http://localhost:11311/dart_sdk.js:39307:13) at http://localhost:11311/dart_sdk.js:34814:9

    opened by hemanthkb97 5
  • Unable to load asset: packages/flutter_google_places/assets/google_white.png

    Unable to load asset: packages/flutter_google_places/assets/google_white.png

    RaisedButton(
                            child: Text(
                              "location"
                            ),
                            onPressed:  () async {
                                Prediction prediction = await PlacesAutocomplete.show(
                                context: context,
                                apiKey: "AIzaSyDSOCqUpchX-xIleHNHQwKZS_Jda64fzxg",
                                mode:  Mode.overlay, // Mode.overlay
                                language: "en",
                                components: [Component(Component.country, "us")]);
                            },
                          ),
    

    When I click the button, my ios simulator hangs and after I reload the simulator, it shows the error below. Please advise thanks!

    ════════ Exception caught by image resource service ════════════════════════════ The following assertion was thrown resolving an image codec: Unable to load asset: packages/flutter_google_places/assets/google_white.png

    When the exception was thrown, this was the stack #0 PlatformAssetBundle.load package:flutter/…/services/asset_bundle.dart:221 #1 AssetBundleImageProvider._loadAsync package:flutter/…/painting/image_provider.dart:664 #2 AssetBundleImageProvider.load package:flutter/…/painting/image_provider.dart:648 #3 ImageProvider.resolveStreamForKey. package:flutter/…/painting/image_provider.dart:501 ... Image provider: ExactAssetImage(name: "packages/flutter_google_places/assets/google_white.png", scale: 2.5, bundle: null)

    opened by geraldspacelim 5
  • List<dynamic>' is not a subtype of type 'PlaceDetails'

    List' is not a subtype of type 'PlaceDetails'

    getDetailsByPlacedId is throwing an exception: "Exception has occurred. _TypeError (type 'List' is not a subtype of type 'PlaceDetails')" Stack trace shows it is on PlaceDetails.fromJson in this section of places.dart:

      factory PlacesDetailsResponse.fromJson(Map json) => json != null
          ? PlacesDetailsResponse(
              json['status'],
              json['error_message'],
              json['result'] != null ? PlaceDetails.fromJson(json['result']) : [],
              json['html_attributions'] != null
                  ? (json['html_attributions'] as List)?.cast<String>()
                  : [])
          : null;
    
    opened by dereklakin 5
  • Distance matrix API integration

    Distance matrix API integration

    ✨ What kind of change does this PR introduce? (Bug fix, feature, docs update...) Calculation distance between origin and destination using Google's Distance Matrix API

    ⤵️ What is the current behavior? Now this package provides API endpoint to accepts API request like this https://maps.googleapis.com/maps/api/distancematrix/json?origins=23.72116,90.394435|23.753550, 90.373797&destinations=23.726346,90.377117|23.761775,90.481922&key="API___KEY"

    Dart implementation example final GoogleDistanceMatrix distanceMatrix = GoogleDistanceMatrix(apiKey: 'API___KEY'); List<Location> origins = [Location(23.721160, 90.394435),Location(23.732322, 90.385142),]; List<Location> destinations = [ Location(23.726346, 90.377117),Location(23.748519, 90.403121),]; DistanceResponse responseForLocation =await distanceMatrix.distanceWithLocation(origins,destinations,);

    🆕 What is the new behavior (if this is a feature change)? APIs for calculating distance by both Location and Address

    💥 Does this PR introduce a breaking change? No.

    🐛 Recommendations for testing I havn't wrote any test but debugged every API integrations

    📝 Links to relevant issues/docs https://developers.google.com/maps/documentation/distance-matrix/start

    opened by 1abid 5
  • How I can consume Google map web services API in my flutter APP

    How I can consume Google map web services API in my flutter APP

    I am new in Flutter, and I have pretty good knowledge of using Google maps APIs for native Android Apps. However, in my flutter app I need Google Places search Auto-complete. I came across to this plugin it consumes google maps APIs such as directions, places and geocoding using Google web services. My question is having low understanding and experiences in setting up web services for google maps API, how I can use plugin in my flutter app? For example, if I had to use places API in android I would have enabled Goole Places SDK in cloud console and generate an API restricting for Android App. But for flutter both Android and iOS is going to use same services from web API call. what should I do? And right now I have no backend knowledge to set up a domain to use while creating the API from console.

    opened by 1abid 5
  • unable to import

    unable to import

    It seems that I am unable to import from this package. image

    my pubspec includes the correct line, I think...

      location: ^1.1.7
      google_maps_webservice: ^0.0.3
    

    I have no trouble using , e.g., the location package. Is this a problem with the package, or a problem in my configuration and usage?

    opened by dss539 5
  • Breaking changes in http package

    Breaking changes in http package

    Screenshot 2021-03-13 at 01 27 10

    The code sample in my Stateful widget

    
     GoogleMapsPlaces places = new GoogleMapsPlaces(apiKey: AppConstants.api_key);
    
    

    It seems to be a problem with package:http/http.dart expecting a Uri but a String is given instead.

      @protected
      Future<Response> doGet(String url, {Map<String, dynamic> headers}) {
        return httpClient.get(url, headers: headers);
      }
    

    I think the correct code is supposed to be

      @protected
      Future<Response> doGet(String url, {Map<String, dynamic> headers}) {
        return httpClient.get(Uri.encodeFull(url), headers: headers);
      }
      
      @protected
      Future<Response> doPost(
        String url,
        String body, {
        Map<String, dynamic> headers,
      }) {
        final postHeaders = {
          'Content-type': 'application/json',
        };
        if (headers != null) postHeaders.addAll(headers);
        return httpClient.post(Uri.encodeFull(url), , body: body, headers: postHeaders);
      }
    
    
    opened by Cmion 4
  • Is this package handle session token by default?

    Is this package handle session token by default?

    Is this package handle session token by default? or I should create a token and pass to sessionToken param while using autocomplete api?

    my code

     var response = await places!.autocomplete(
              //sessionToken  should I pass a custom session token here or not?
              query,
              language: "en",
              types: ['address'],
              components: [Component("country", "ca")]);
    
          if (response.isOkay) {
          //handle the response
          }
    
    opened by ziagit 0
  • xmlHttpRequest Error

    xmlHttpRequest Error

    Hi i am using this project to get the places but it will give me the error which is.

    Error: XMLHttpRequest error.
      C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 910:28                get current
    packages/http/src/browser_client.dart 69:22                                                                                    <fn>
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1685:54                                              runUnary
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 159:18                                        handleValue
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 766:44                                        handleValueCallback
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13                                        _propagateToListeners
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 592:7                                         [_complete]
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11                                         _cancelAndValue
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1288:7                                             <fn>
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14  _checkAndCall
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39  dcall
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37301:58                              <fn>
    
    
      at Object.createErrorWithStack (http://localhost:50954/dart_sdk.js:5080:12)
      at Error._throw (http://localhost:50954/dart_sdk.js:20337:18)
      at Error.throwWithStackTrace (http://localhost:50954/dart_sdk.js:20334:18)
      at async._AsyncCallbackEntry.new.callback (http://localhost:50954/dart_sdk.js:40851:18)
      at Object._microtaskLoop (http://localhost:50954/dart_sdk.js:40708:13)
      at _startMicrotaskLoop (http://localhost:50954/dart_sdk.js:40714:13)
      at http://localhost:50954/dart_sdk.js:36191:9
    

    i dont know why it give me this error :

    flutter doctor :

    C:\src\flutter\bin\flutter.bat doctor --verbose
    [√] Flutter (Channel stable, 2.10.5, on Microsoft Windows [Version 10.0.19044.1826], locale en-US)
        • Flutter version 2.10.5 at C:\src\flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 5464c5bac7 (3 months ago), 2022-04-18 09:55:37 -0700
        • Engine revision 57d3bac3dd
        • Dart version 2.16.2
        • DevTools version 2.9.2
    

    kindly look into this matter. i really appreciate that

    opened by adnan-branch 3
  • Suspected issue, needs confirmation

    Suspected issue, needs confirmation

    https://github.com/lejard-h/google_maps_webservice/blob/7b10f467cfedea75de13c8c3419fdec8cd06098a/lib/src/places.dart#L804

    Hello, my Android Studio editor reports errors from the lines above as shown in the picture below image

    I haven't tested these errors in my app to confirm the errors are actually an issue. Thanks.

    opened by andesappal 0
  • searchNearbyWithRankBy fails with an error

    searchNearbyWithRankBy fails with an error

    
    For solutions, see https://dart.dev/go/unsound-null-safety
    lib/ui/routes/select_location_on_map_route.dart:824:97: Error: Too many positional arguments: 0 allowed, but 2 found.
    Try removing the extra positional arguments.
                       PlacesSearchResponse response = await places.searchNearbyWithRankBy( Location(latitude, longitude), "distance", keyword: '' );
    

    Even though the location and rank is required parameters. Please any help will be appreciated

    opened by Muniru0 0
Owner
Hadrien Lejard
Front end developer at @leftyio with @dart-lang @angular @flutter
Hadrien Lejard
This is a Flutter package that uses the Google Maps API to make a TextField that tries to autocomplete places as the user types, with simple smooth animations, making a nice UI and UX.

search_map_place This is a Flutter package that uses the Google Maps API to make a TextField that tries to autocomplete places as the user types, with

Lucas Bernardi 127 Oct 22, 2022
A migration of Google Maps Application with Flutter & Google Maps APIs including: Maps SDK for Android & IOS, Places API & polylines

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

TAD 1 Mar 4, 2022
A Flutter example to use Google Maps in iOS and Android apps via the embedded Google Maps plugin Google Maps Plugin

maps_demo A Flutter example to use Google Maps in iOS and Android apps via the embedded Google Maps plugin Google Maps Plugin Getting Started Get an A

Gerry High 41 Feb 14, 2022
Flutter package to enable clustering of location markers on Google Maps using widgets specific to each location.

flutter_google_maps_widget_cluster_markers This widget implements a very specific adaptation of google_maps_cluster_manager, allowing different ,marke

Kek Tech 2 Jan 6, 2023
A plugin that offers widgets for Wear OS by Google

Flutter Wear Plugin A plugin that offers Flutter support for Wear OS by Google (Android Wear). To use this plugin you must set your minSdkVersion to 2

Flutter Community 114 Dec 18, 2022
Flutter Maps A Flutter app using Google Maps SDK & Directions API

Flutter Maps A Flutter app using Google Maps SDK & Directions API Plugins The plugins used in this project are: google_maps_flutter geolocator flutter

Salsabil Mohamed Hemada 1 Jul 15, 2022
A flutter plugin for Google Maps

IMPORTANT: This plugin is no longer under development Why? We initially built this plugin to fill an early gap in flutter. Since then, Google has made

AppTree Software, Inc 415 Dec 29, 2022
Flutter Google Maps Tutorial

Flutter Google Maps Tutorial YouTube Video Setup Get an API Key at https://cloud.google.com/maps-platform/ Enable Maps SDK for Android, Maps SDK for i

Marcus Ng 85 Nov 30, 2022
Flutter Tutorial - Google Map with Live Location Tracking

Flutter Tutorial - Google Map with Live Location Tracking Build Google Map app with Live Location Tracking in Flutter. ✌   App Preview Android Preview

Samuel Adekunle 10 Dec 22, 2022
Flutter Google Map Example - Day 41

Flutter Google Map Example - Day 41 class Afgprogrammer extends Flutter100DaysOfCode { video() { return { "title": "Flutter Google Map Exa

Mohammad Rahmani 74 Jan 3, 2023
A Flutter app using Google Maps SDK & Directions API

Flutter Maps A Flutter app using Google Maps SDK & Directions API Plugins The plugins used in this project are: google_maps_flutter geolocator flutter

Youhaan bootwala 1 Mar 18, 2022
A Flutter app using Google Maps SDK & Directions API

Flutter Maps A Flutter app using Google Maps SDK & Directions API Plugins The plugins used in this project are: google_maps_flutter geolocator flutter

Varun CN 2 Apr 19, 2022
Easy Google Maps for Flutter

easy_google_maps Easy Google Maps for Flutter on Web and Mobile Getting Started Mobile Follow setup for Mobile Here Web Good to go! EasyGoogleMaps(

Rody Davis 69 Jul 19, 2022
Flutter Google Map Example

Flutter Google Map Example A Flutter application demonstrate google map. Preview Listener and Marker Compass MapTypes Plugin google_maps_flutter from

Bhavik Makwana 67 Sep 14, 2021
Place picker on Google Maps for Flutter

Google Maps Place Picker A Flutter plugin which provides 'Picking Place' using Google Maps widget. The project relies on below packages. Map using Flu

Terry Kwon 178 Dec 16, 2022
How To Integrate Customized Google Map in Flutter

How To Integrate Customized Google Map in Flutter Let’s develop a customised Google Maps for the best user experience. Visit : https://medium.com/flut

Jaimil Patel 19 Dec 6, 2022
A car rental flutter application using firebase and google maps API

A car sharing & rental app using Flutter, Firebase & Google Maps APIs ?? About the App ?? hopOn is flutter based application for car sharing and renta

Shivani Singh 97 Dec 30, 2022
Simple flutter app demonstrating usage of Google Maps

flutter_maps_example Get an API key at GoogleCloud. Enable Google Map SDK for ea

Tornike Gogberashvili 0 Nov 23, 2022
A Flutter plugin for integrating Google Maps in iOS, Android and Web applications

flutter_google_maps A Flutter plugin for integrating Google Maps in iOS, Android and Web applications. It is a wrapper of google_maps_flutter for Mobi

MarchDev Toolkit 86 Sep 26, 2022