Flutter Google Maps Example

As a part of our flutter tutorial series, we’re going to learn how to display google maps in a flutter with example.

flutter-google-maps-tutorial
flutter-google-maps-tutorial

What we’ll learn?

  • Learn how to create Google Map Key and Enable Required Services
  • Display Google Map in flutter App
  • Fetching Current Location using Location Plugin
  • Displaying Marker on Google Map
  • Update Marker location (with current position) + animate Camera

What do you need?


Flutter Google Maps Example

 

To work with our example, we need to create a new flutter project or we can use any existing project.

flutter create learnflutter
cd learnflutter

Once the plugin is added, we need to add the required packages inside pubspec.yaml

dependencies:
  google_maps_flutter:
  location:

Then execute flutter pub get to install all required packages

Creating Google Maps API Key

To Display Google Map, we must need API Key.

Step 1:

Step 2: Enable Service

We require

  • Maps SDK for Android
  • Maps SDK for iOS

Step 3: Create API Key & copy it

Step 4: Update project/android/app/src/main/AndroidManifest.xml

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


flutter-google-map-example-1
flutter-google-map-example-1

Display Google Maps using Flutter

import 'dart:async';

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

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Completer<GoogleMapController> _controller = Completer();

  CameraPosition _currentPosition = CameraPosition(
    target: LatLng(13.0827, 80.2707),
    zoom: 12,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Google Maps"),
      ),
      body: Container(
        height: double.infinity,
        width: double.infinity,
        child: GoogleMap(
          initialCameraPosition: _currentPosition,
          onMapCreated: (GoogleMapController controller) {
            _controller.complete();
          },
        ),
      ),
    );
  }
}

Code Explanation:

  • We used GoogleMap() to render the map, which requires an initial position.
  • We created a static location and fed into it.

flutter-google-map-example-2
flutter-google-map-example-2

Google Maps + Market + Current Location


class _HomePageState extends State<HomePage> {
  double _lat = 13.0827;
  double _lng = 80.2707;
  Completer<GoogleMapController> _controller = Completer();
  Location location = new Location();
  bool _serviceEnabled;
  PermissionStatus _permissionGranted;
  CameraPosition _currentPosition;

  @override
  initState() {
    super.initState();
    _currentPosition = CameraPosition(
      target: LatLng(_lat, _lng),
      zoom: 12,
    );
  }

  _locateMe() async {
    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }
    await location.getLocation().then((res) async {
      final GoogleMapController controller = await _controller.future;
      final _position = CameraPosition(
        target: LatLng(res.latitude, res.longitude),
        zoom: 12,
      );
      controller.animateCamera(CameraUpdate.newCameraPosition(_position));
      setState(() {
        _lat = res.latitude;
        _lng = res.longitude;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Google Maps"),
      ),
      body: Container(
        height: double.infinity,
        width: double.infinity,
        child: GoogleMap(
          initialCameraPosition: _currentPosition,
          markers: {
            Marker(
              markerId: MarkerId('current'),
              position: LatLng(_lat, _lng),
            )
          },
          onMapCreated: (GoogleMapController controller) {
            _controller.complete(controller);
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.location_searching),
        onPressed: () => _locateMe(),
      ),
    );
  }
}

Code Explanation:

  • As in the previous code, we displayed a map with the default location.
  • When the user pressed the floating action button, we’re fetching the current location and updated the marker.