Saturday, October 10, 2020

Flutter Google Maps | Geolocator | Geocoder

Flutter Google Maps

What you'll build
you'll build a mobile app featuring a Google Map using the Flutter SDK. Your app will:
  • Display a Google Map
  • Add a Image and Text 
  • Dispay infoworld
  • Display this data as markers as well as custom marker also on the Map,
  • polygon
  • Retrieve map data from a web service
  • Get User Address
  • Latitude to convert Address
  • Hide map api key
Important Step
Step :#1 [ Location permissions ]

Important Library
https://pub.dev/packages/google_maps_flutter
  google_maps_flutter: ^1.1.1

https://pub.dev/packages/geocoder/install
  geocoder: ^0.2.1

https://pub.dev/packages/geolocator/install
  geolocator: ^6.1.14


Official Doc
https://developers.google.com/maps/documentation/android-sdk/location

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

       android:usesCleartextTraffic="true"


Step :#2 [ change gradle.properties ]
android.enableDexingArtifactTransform=false


Step :#3 [ Add Key ]

        <meta-data android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyAIZ40uk5L-Q"/>


Step :#4 [ It's always not mandatory if sdk is 21 ]
android\app\build.gradle       

        minSdkVersion 21
        multiDexEnabled true


Step :#5 
1. If you want to test Physical device? It's mendartoy update or clear cache of Google play service.
2. Test with Emulator do Install it


Step :#6 [ Hiding API_KEY ]
First, put your key in the android/local.properties

MAPS_API_KEY= Paste here api key


In android/app/build.gradle , add this line

def localPropertyApiToken = localProperties.getProperty("MAPS_API_KEY")
def systemEnvApiToken = System.getenv('MAPS_API_KEY')
def MAPS_API_KEY = localPropertyApiToken != null ? localPropertyApiToken : systemEnvApiToken


In android/app/build.gradle , add this line

manifestPlaceholders = [MAPS_API_KEY: MAPS_API_KEY]


In android\app\src\main\AndroidManifest.xml , add this line

<meta-data android:name="com.google.android.geo.API_KEY"
    android:value="${MAPS_API_KEY}"/>





Happy Coding :)
...............................................................................................................................................................................................................................
Basic Setup for Google Maps 
Create and  setup a new Google Cloud Platform (GCP) project

1. Go to Google Cloud Platform Console. 
https://console.cloud.google.com/?pli=1



2. Go to Project Selection dialog-box and click New Project.


3. Enter the project



Enabling APIs
Now, search for Maps and enable Maps SDK for both platforms.









Same process for iOS





You will also need the Directions API while drawing the routes. So enable that as well.


Generating an API key

You will need an API key for integrating Google Maps into your app.
Go to APIs & Services from the left menu and select Credentials.

Click CREATE CREDENTIALS and select API key.



This will generate an API key for the project, you will need this in the next step.


Select Apis





Set up the Flutter project
Create a new Flutter project.

flutter create google_map_poly_distance

cd google_map_poly_distance


Setp #1 [ dependency  ]
The first step is to add the Google Maps Flutter plugin as a dependency in the pubspec.yaml file. The package is available as google_maps_flutter on pub.dartlang.org.
https://pub.dev/packages/google_maps_flutter  Once you do that, you need to run flutter packages get.

  google_maps_flutter: ^1.1.1


Setp #2 [API KEY ]
The next step is getting an API key for both Android and iOS. For Android, follow the instructions at Maps SDK for Android, Get API Key. Once you have your API key,  add it to your Flutter app in the application manifest (android/app/src/main/AndroidManifest.xml), as follows

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



Copy the API key paste above



iOS setup
Navigate to the file ios/Runner/AppDelegate.swift and replace the whole code with the following:

import UIKit
import Flutter
import GoogleMaps
  
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    //Add your Google Maps API Key here
   // GMSServices.provideAPIKey("AIzddR-h27Ypjn0kgYJEP6wWg")

    GMSServices.provideAPIKey("YOUR KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Also, add the following to ios/Runner/Info.plist file:
<key>io.flutter.embedded_views_preview</key> 
<string>YES</string>

To get the location permission, add the following to the same file:

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>

//
<key>io.flutter.embedded_views_preview</key>
<string>YES</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>

//
Setp #3 [Adding a GoogleMap widget]
Now you are ready to add a GoogleMap widget! Run flutter clean to make sure the API key changes are picked up on the next build. Then, add a GoogleMap widget that covers the entire screen.

Setp #4 [ Code Here... ]
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      title: Text('Flutter Google Maps'),
    ),
    body: GoogleMap(  
      initialCameraPosition: CameraPosition(  
        target: LatLng(19.043470, 72.819536),
        zoom: 14.0
      )
    ),
    );
  }
}

Basic Code

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.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> {
  GoogleMapController mapController;
  CameraPosition initialLocation = CameraPosition(target: LatLng(0.0, 0.0));

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: GoogleMap(
        initialCameraPosition: initialLocation,
        myLocationEnabled: true,        //give locations circle on the right corner of top
        myLocationButtonEnabled: false,
        mapType: MapType.normal,
        zoomGesturesEnabled: true,
        zoomControlsEnabled: false,         // + or - disable button on right side bottom corner
        onMapCreated: (controller) {
          mapController = controller;
        },
      ),
    );
  }
}
Happy Coding :)
...............................................................................................................................................................................................................................
Fetching current location
There is a nice plugin for Flutter, known as geolocator that can help you to fetch user’s current location easily. Add it to your pubspec.yaml file.

https://pub.dev/packages/geolocator/install
  geolocator: ^6.1.14

Code Here
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.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> {
  GoogleMapController mapController;
  CameraPosition initialLocation = CameraPosition(target: LatLng(0.0, 0.0));
  Position currentPosition;

  Future<void> getCurrentLocation() async {
    await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
        .then((Position position) async {
      setState(() {
        currentPosition = position;
        print("CURRENT POSITION: $currentPosition");


        mapController.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: LatLng(position.latitude, position.longitude),
              zoom: 18.0,
            ),
          ),
        );
      });
    }).catchError((e) {
      print(e);
    });
  }

  @override
  void initState() {
  super.initState();
  getCurrentLocation();
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GoogleMap(
        onTap: (tapped) => ({tapped.latitude,tapped.longitude }),

        initialCameraPosition: initialLocation,
        myLocationEnabled: true,                //give locations circle on the right corner of top
        myLocationButtonEnabled: false,
        zoomControlsEnabled: false,         // or disable button on right side bottom corner
        mapType: MapType.normal,
        zoomGesturesEnabled: true,

        onMapCreated: (GoogleMapController controller) {
          mapController = controller;
        },
      ),
    );
  }
}

...............................................................................................................................................................................................................................
Drawing Route Lines on Google Maps Between Two Locations in Flutter
using Flutter Polyline Points Package

Add a dependencies 
https://pub.dev/packages/flutter_polyline_points/install

  flutter_polyline_points: ^0.2.4


Completer<GoogleMapController> _controller = Completer();
// this set will hold my markers
Set<Marker> _markers = {};

// this will hold the generated polylines
Set<Polyline> _polylines = {};

// this will hold each polyline coordinate as Lat and Lng pairs
List<LatLng> polylineCoordinates = [];

// this is the key object - the PolylinePoints
// which generates every polyline between start and finish

PolylinePoints polylinePoints = PolylinePoints();
String googleAPIKey = “<YOUR_API_KEY>”;

// for my custom icons
BitmapDescriptor sourceIcon;
BitmapDescriptor destinationIcon;





...............................................................................................................................................................................................................................
Geocoding 
Geocoding is a technique by which the address of a place can be converted to their coordinates (latitude & longitude) and vice versa.



...............................................................................................................................................................................................................................
Example :#1[ Add a Text and Image]

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: Stack(
          children: [
            GoogleMap(
                initialCameraPosition: CameraPosition(
                    target: LatLng(19.043470, 72.819536), zoom: 14.0)),
            Container(
              width: 150.0,
              height: 150.0,
              alignment: Alignment.topCenter,
              child: Image.asset('assets/images/d.jpg', ),
            ),
            Container(
              alignment: Alignment.bottomCenter,
              child: Text(
                'Flutter Google Maps',
                style: Theme.of(context).textTheme.headline3,
              ),
            )
          ],
        ));
  }
}

Happy Coding :)
...............................................................................................................................................................................................................................
Example :#2 [ Add a Marker] 

import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.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> {
  var myMarkers = HashSet<Marker>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: GoogleMap(
          markers: myMarkers,
          initialCameraPosition:
          CameraPosition(target: LatLng(19.043470, 72.819536), zoom: 14.0),

          onMapCreated: (GoogleMapController googleMapController) {
            setState(() {
              myMarkers.add(Marker(
                markerId: MarkerId('1'),
                position: LatLng(19.043470, 72.819536),
              ));
            });
          },
        ));
  }
}

.......................................................
Clean Code...

import 'dart:async';
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.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> {
  static const LatLng _latLng = LatLng(19.043470, 72.819536);

  var myMarkers = HashSet<Marker>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: GoogleMap(
          initialCameraPosition: CameraPosition(target: _latLng, zoom: 14.0),
          markers: myMarkers,
        ));
  }
}
..............................
Another code of marker for two destionations
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

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

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

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

class _HomeState extends State<Home> {
  GoogleMapController googleMapController;
  CameraPosition cp =
      CameraPosition(target: LatLng(19.053766, 72.841979), zoom: 14.000);

  final Set<Marker> marker = Set();
  final LatLng sourceLatLong = LatLng(19.053766, 72.841979);
  final LatLng destinationLatLong = LatLng(19.057342, 72.826705);

  @override
  void initState() {
    super.initState();
    marker.add(Marker(
        markerId: MarkerId("1"),
        position: sourceLatLong,
        infoWindow: InfoWindow(title: "Source Mumbai"),
        icon: BitmapDescriptor.defaultMarker,
        visible: true));

    marker.add(Marker(
      markerId: MarkerId("2"),
      position: destinationLatLong,
      infoWindow: InfoWindow(title: "BKC"),
      icon: BitmapDescriptor.defaultMarker,
      visible: true,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return GoogleMap(
      initialCameraPosition: cp,
      myLocationEnabled: true,
      mapType: MapType.normal,
      onMapCreated: (GoogleMapController controller) {
        googleMapController = controller;
      },
      markers: marker,
    );
  }
}


Happy Coding :)
...............................................................................................................................................................................................................................
Example :#3[ InfoWindow ]

import 'dart:async';
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.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> {
  Completer<GoogleMapController> _controller = Completer();
  static const LatLng _latLng = LatLng(19.043470, 72.819536);

  var myMarkers = HashSet<Marker>();

  void _onMapCreated(GoogleMapController googleMapController) {
    _controller.complete(googleMapController);
    setState(() {
      myMarkers.add(Marker(
          markerId: MarkerId('1'),
          position: _latLng,
          infoWindow: InfoWindow(
              title: 'Taj Land End, Mumbai', snippet: '5 star Rating')));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: GoogleMap(
          initialCameraPosition: CameraPosition(target: _latLng, zoom: 14.0),
          markers: myMarkers,
          onMapCreated: _onMapCreated,
        ));
  }
}


Happy Coding :)
...............................................................................................................................................................................................................................
Example :#4 [ Add a Custom Marker ]

import 'dart:async';
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MaterialApp(home: 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> {
  Completer<GoogleMapController> _completer = Completer();
  static const LatLng _latLng = LatLng(19.077098, 72.851786);

  var myMarkers = HashSet<Marker>();

  void _onMapCreated(GoogleMapController googleMapController) async {
    _completer.complete(googleMapController);
    setState(() {
      myMarkers.add(Marker(
          markerId: MarkerId('1'), 
          position: _latLng, 
          icon: bitmapDescriptor,
          infoWindow: InfoWindow(  
            title: 'Grand Hyatt, Mumbai',
            snippet: '5 Start Rating'
          )
          ),
          );
       });
  }

  BitmapDescriptor bitmapDescriptor;
  getCustomMarker() async {
    bitmapDescriptor = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration.empty, 'assets/images/do.jpg');
  }

  @override
  void initState() {
    super.initState();
    getCustomMarker();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Google Maps'),
      ),
      body: GoogleMap(
        initialCameraPosition: CameraPosition(target: _latLng, zoom: 14),
        markers: myMarkers,
        onMapCreated: _onMapCreated,
      ),
    );
  }
}

Happy Coding :)
...............................................................................................................................................................................................................................
Example :#5 [ polygon ]

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MaterialApp(home: 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> {
static const LatLng _latLng = LatLng(37.43296265331129, -122.08832357078792);

Set<Polygon> myPolygon() {
  var polygonCoords = List<LatLng>();    
  polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43006265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43006265331129, -122.08332357078792));
  polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));

  var polygonSet = Set<Polygon>();
  polygonSet.add(
    Polygon(
      polygonId: PolygonId('1'),
      points: polygonCoords,
      strokeColor: Colors.red,
      )
      );
  return polygonSet;
}
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Google Maps'),
      ),
      body: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(target: _latLng, zoom: 14),
        polygons: myPolygon(),
      ),
    );
  }
}

Happy Coding :)
...............................................................................................................................................................................................................................
Example :#6

...............................................................................................................................................................................................................................
Example :#7
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MaterialApp(home: 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> {
  var myMarkers = HashSet<Marker>();
  BitmapDescriptor bitmapDescriptor;
  getCustomMarker() async {
    bitmapDescriptor = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration.empty, 'assets/images/do.jpg');
  }

  @override
  void initState() {
    super.initState();
    getCustomMarker();
  }
  Set<Polygon> myPolygon() {
  var polygonCoords = List<LatLng>();    
  //polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));
   polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43006265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43006265331129, -122.08332357078792));
  polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));

  var polygonSet = Set<Polygon>();
  polygonSet.add(
    Polygon(
      polygonId: PolygonId('1'),
      points: polygonCoords,
      strokeColor: Colors.red,
      )
      );
  return polygonSet;
}
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: Stack(
          children: [
            GoogleMap(
              initialCameraPosition: CameraPosition(
                  target: LatLng(37.43296265331129, -122.08832357078792), zoom: 14),
              onMapCreated: (GoogleMapController googleMapController) {
                setState(() {
                  myMarkers.add(Marker(
                      markerId: MarkerId('1'),
                      position: LatLng(19.082089, 72.877497),
                      infoWindow: InfoWindow(
                        title: 'Hello World',
                        snippet: 'please share Address',
                      ),
                      onTap: () {
                        print('Marker tabes');
                      },
                      icon: bitmapDescriptor));
                });
              },
              markers: myMarkers,
              polygons: myPolygon(),
            ),
            Container(
              alignment: Alignment.topCenter,
              child: Image.asset('assets/images/d.jpg'),
            ),
            Container(
              child: Text(
                'Flutter Google Maps',
                style: TextStyle(fontSize: 35.0, fontWeight: FontWeight.bold),
              ),
              alignment: Alignment.bottomCenter,
            )
          ],
        ));
  }
}

Happy Coding :)
....................................................................................................................................................................................................................................
Example :#8 [Flutter Geolocation - Fetch the User's Current Location ] 

Library

geolocator: ^6.1.8
https://pub.dev/packages/geolocator

Add the following to your "gradle.properties" file:

android.useAndroidX=true
android.enableJetifier=true

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
.............
Code here
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

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

class _HomeState extends State<Home> {
  String latitudeData = "";
  String longitudeData = "";

  @override
  void initState() {
    getCurrentLocations();
    super.initState();
  }

  getCurrentLocations() async {
    final geolocator = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
       setState(() {
      latitudeData = '${geolocator.latitude}';
      longitudeData = '${geolocator.longitude}';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Geolocation'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            Text(latitudeData),
            Text(longitudeData),
          ],
        ),
      ),
    );
  }
}

Happy Coding :)
....................................................................................................................................................................................................................................
Example:  #9[ Get User Current Location Using Flutter]

Add dependencies -
https://pub.dev/packages/geolocator/install
  geolocator: ^6.1.13

AndroidManifest.xml
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

Important url for
https://developer.android.com/training/basics/network-ops/connecting
https://developer.android.com/training/location/permissions#reminder-background-location-grant

.............................................
Code Here
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.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 locationsMessage = "";

  Future<void> getCurrentLocations() async {
    final position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    print(position);

    final lat = position.latitude;
    final lon = position.longitude;
    setState(() {
      locationsMessage = "Latitude : $lat, Longitude: $lon";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Location Services"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.location_on,
              size: 45.0,
              color: Colors.blue,
            ),
            const SizedBox(height: 20.0),
            const Text('Get user Locations',
                style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold)),
            const SizedBox(height: 20.0),
            Text("Position: $locationsMessage"),
            FlatButton(
              onPressed: () => getCurrentLocations(),
              color: Colors.black,
              child: const Text("Open Maps",
                  style: TextStyle(
                      color: Colors.white, fontWeight: FontWeight.bold)),
            )
          ],
        ),
      ),
    );
  }
}

Another Code 
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String locationMessage = "";

  Future<void> getLocations() async {
    final position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    print(position);
    setState(() {
      locationMessage = "${position.latitude}, ${position.longitude}";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Hello'),
      ),
      body: Center(
        child: Column(
          children: [
            Text(locationMessage),
            RaisedButton(
              onPressed: () => getLocations(),
              child: const Text("Get Address"),
            ),
          ],
        ),
      ),
    );
  }
}
Happy Coding :)
....................................................................................................................................................................................................................................
Example:  #10[ Get User Address In Flutter]

dependencies
  geolocator: ^6.1.13
  geocoder: ^0.2.1

https://pub.dev/packages/geocoder/install
https://pub.dev/packages/geolocator/install

Code Here

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoder/geocoder.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> {
  Position positions;
  StreamSubscription<Position> streamSubscription;
  Address address;

  @override
  void initState() {
    super.initState();
    streamSubscription = Geolocator.getPositionStream(
            distanceFilter: 10, desiredAccuracy: LocationAccuracy.high)
        .listen((Position position) {
      setState(() {
        positions = position;
        final coordinates = Coordinates(position.latitude, position.longitude);
        convertCoordinateToAddress(coordinates)
            .then((value) => address = value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Get Address")),
      body: Center(
        child: Column(
          children: [
            Text("Long ${positions?.latitude ?? '-'},${positions?.longitude ?? '-'}"),
            //Text("${address?.addressLine ?? '-'}"),
            Text("Current Address : ${address?.addressLine?? '-'}"),
            Text("Dist : ${address?.locality?? '-'}"),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    streamSubscription.cancel();
  }

  Future<Address> convertCoordinateToAddress(Coordinates coordinates) async {
    final addresses =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    return addresses.first;
  }
}
Note  - Testing device should be physical device
and update Google playstore apps or clear cache
 

Another Code Here

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  String address1 = "";
  String address2 = "";

  @override
  void initState() {
    super.initState();
    getAddress();
  }

  Future<void> getAddress() async {
    final coordinates = Coordinates(12.902030, 77.593540);
    final address =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    setState(() {
      address1 = address.first.addressLine;
      address2 = address.first.locality;
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Get User Locations!"),
      ),
      body: Center(
        child: Column(
          children: [
            Text(address1),
            Text(address2),
          ],
        ),
      ),
    );
  }
}
...........................................
Another Code 

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String locationMessage = "";
  String address1 = "";
  String address2 = "";

  Future<void> getLocations() async {
    final position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    print(position);
    setState(() {
      locationMessage = "${position.latitude}, ${position.longitude}";
    });
  }

  Future<void> getAddress() async {
    final coordinates = Coordinates(37.4219983, -122.084);
    final addresses =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    
    setState(() {
      address1 = addresses.first.addressLine;
      address2 = addresses.first.locality;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Hello'),
      ),
      body: Center(
        child: Column(
          children: [
            Text(locationMessage),
            RaisedButton(
              onPressed: () => getLocations(),
              child: const Text("Get Longitude"),
            ),
            Text(address1),
            Text(address2),
            RaisedButton(
              onPressed: () => getAddress(),
              child: const Text("Get Address"),
            ),

          ],
        ),
      ),
    );
  }
}

Happy Coding :)
....................................................................................................................................................................................................................................
Example:  #11[]

https://pub.dev/packages/google_maps_flutter
google_maps_flutter 1.1.1 

Google Cloud console
https://console.cloud.google.com/apis/dashboard?project=fluttermaps-302110




API Key



Choose Here as Restrict Key




Maps for Android
Maps for iOS










Happy Coding :)
....................................................................................................................................................................................................................................
Example:  #12[]

import 'dart:core';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart' as geocoder;
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  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> {
   GoogleMapController googleMapController;
   Position position;
   String addresslocations;
   String country;
   String postalCode;

  Map<MarkerId, Marker> markers = Map<MarkerId, Marker>();

  void getMarkers(double lat, double long) {
    MarkerId markerId = MarkerId(lat.toString() + long.toString());
    Marker marker = Marker(
        markerId: markerId,
        position: LatLng(lat, long),
        icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan),
        infoWindow: InfoWindow(snippet: 'Address'));
    setState(() {
      markers[markerId] = marker;
    });
  }

  Future<void> getCurrentLocations() async {
    Position currentPosition =
        await GeolocatorPlatform.instance.getCurrentPosition();
    setState(() {
      position = currentPosition;
    });
  }

  @override
  void initState() {
    super.initState();
    getCurrentLocations();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: Container(
          child: Column(
            children: [
              SizedBox(
                height: 600.0,
                child: GoogleMap(
                  onTap: (tapped) async {
                    final coordinates = new geocoder.Coordinates(
                        tapped.latitude, tapped.longitude);

                    var address = await geocoder.Geocoder.local
                        .findAddressesFromCoordinates(coordinates);
                    var firstAddress = address.first;

                    getMarkers(tapped.latitude, tapped.longitude);
                    await FirebaseFirestore.instance
                        .collection('locatioon')
                        .add({
                      'latitude': tapped.latitude,
                      'longitude': tapped.longitude,
                      'Address': firstAddress.addressLine,
                      'Country Code': firstAddress.countryName,
                      'PostalCode': firstAddress.postalCode
                    });
                    setState(() {
                      country = firstAddress.countryName;
                      postalCode = firstAddress.postalCode;
                      addresslocations = firstAddress.addressLine;
                    });
                  },
                  mapType: MapType.hybrid,
                  compassEnabled: true,
                  trafficEnabled: true,
                  onMapCreated: (GoogleMapController controller) {
                    setState(() {
                      googleMapController = controller;
                    });
                  },
                  initialCameraPosition: CameraPosition(
                      target: LatLng(position.latitude.toDouble(),
                          position.longitude.toDouble()),
                      zoom: 15.0),
                  markers: Set<Marker>.of(markers.values),
                ),
              ),
              Text('Address: $addresslocations'),
              Text('Postal: $postalCode'),
              Text('Country: $country'),
            ],
          ),
        ));
  }

  @override
  void dispose() {
    super.dispose();
  }
}


Happy Coding :)

...............................................................................................................................................................................................................................


...............................................................................................................................................................................................................................


...............................................................................................................................................................................................................................

...............................................................................................................................................................................................................................














1 comment: