Skip to content

Draw Shapes on Map

This example presents how to create a Flutter app that draws and displays shapes like polylines, polygons, and points on a map using gem_kit package.

draw_shapes - example Flutter screenshot

draw_shapes - example Flutter screenshot

draw_shapes - example Flutter screenshot

Setup

First, get an API key token, see the Getting Started guide.

Prerequisites

Make sure you completed the Environment Setup - Flutter Examples guide before starting this guide.

Build and Run

Navigate to the draw_shapes directory within the Flutter examples directory. This is the project folder for this example.

Note - the gem_kit directory containing the Maps SDK for Flutter should be in the plugins directory of the example, e.g. example_pathname/plugins/gem_kit - see the environment setup guide above.

Run: flutter pub get

Configure the native parts:

First, verify that the ANDROID_SDK_ROOT environment variable is set to the root path of your android SDK.

In android/build.gradle add the maven block as shown, within the allprojects block, for both debug and release builds:

:lineno-start: 1

    allprojects {
        repositories {
            google()
            mavenCentral()
            maven {
               url "${rootDir}/../plugins/gem_kit/android/build"
            }
        }
    }

in android/app/build.gradle within the android block, in the defaultConfig block, the android SDK version minSdk must be set as shown below.

Additionally, for release builds, in android/app/build.gradle, within the android block, add the buildTypes block as shown:

Replace example_pathname with the actual project pathname

:lineno-start: 1

android {
    defaultConfig {
        applicationId "com.magiclane.gem_kit.examples.example_pathname"
        minSdk 21
        targetSdk flutter.targetSdk
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }
    buildTypes {
        release {
            minifyEnabled false
            shrinkResources false

            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

In the ios/Podfile configuration file, at the top, set the minimum ios platform version to 14 like this:

platform :ios, '14.0'

We recommend you to run these commands after you copy the gem_kit into your project: |flutter clean |flutter pub get |and |cd ios |pod install

Then run the project:

flutter run --debug
or
flutter run --release

App entry and initialization

const projectApiToken = String.fromEnvironment('GEM_TOKEN');

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

This code initializes the projectApiToken with the required authorization token and launches the app.

How It Works

The example app demonstrates the following features:

  • Draw and display polylines, polygons, and points on the map.

  • Handle user interaction through app bar buttons.

draw_shapes - example Flutter screenshot

Note - the gem_kit directory containing the Maps SDK for Flutter should be in the plugins directory of the example, e.g. example_pathname/plugins/gem_kit - see the environment setup guide above.

Run: flutter pub get

Configure the native parts:

First, verify that the ANDROID_SDK_ROOT environment variable is set to the root path of your android SDK.

In android/build.gradle add the maven block as shown, within the allprojects block, for both debug and release builds:

:lineno-start: 1

    allprojects {
        repositories {
            google()
            mavenCentral()
            maven {
               url "${rootDir}/../plugins/gem_kit/android/build"
            }
        }
    }

in android/app/build.gradle within the android block, in the defaultConfig block, the android SDK version minSdk must be set as shown below.

Additionally, for release builds, in android/app/build.gradle, within the android block, add the buildTypes block as shown:

Replace example_pathname with the actual project pathname

:lineno-start: 1

android {
    defaultConfig {
        applicationId "com.magiclane.gem_kit.examples.example_pathname"
        minSdk 21
        targetSdk flutter.targetSdk
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }
    buildTypes {
        release {
            minifyEnabled false
            shrinkResources false

            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

In the ios/Podfile configuration file, at the top, set the minimum ios platform version to 14 like this:

platform :ios, '14.0'

We recommend you to run these commands after you copy the gem_kit into your project: |flutter clean |flutter pub get |and |cd ios |pod install

Then run the project:

flutter run --debug
or
flutter run --release

UI and Map Interaction

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Draw Shapes',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late GemMapController _mapController;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.deepPurple[900],
        title: const Text('Draw Shapes', style: TextStyle(color: Colors.white)),
        actions: [
          IconButton(
              onPressed: _onPolylineButtonPressed,
              icon: const Icon(
                Icons.adjust,
                color: Colors.white,
              )),
          IconButton(
              onPressed: _onPolygonButtonPressed,
              icon: const Icon(
                Icons.change_history,
                color: Colors.white,
              )),
          IconButton(
              onPressed: _onPointsButtonPressed,
              icon: const Icon(
                Icons.more_horiz,
                color: Colors.white,
              ))
        ],
      ),
      body: GemMap(onMapCreated: _onMapCreated, appAuthorization: projectApiToken),
    );
  }

This code defines the main UI elements, including the map and an app bar with buttons to draw polylines, polygons, and points on the map.

Drawing and Displaying Shapes

// The callback for when map is ready to use.
void _onMapCreated(GemMapController controller) async {
  // Save controller for further usage.
  _mapController = controller;
}

// Method to draw and center on a polyline
void _onPolylineButtonPressed() {
  // Create a marker collection
  final markerCollection = MarkerCollection(
      markerType: MarkerType.polyline, name: 'Polyline marker collection');

  // Set coordinates of marker
  final marker = Marker();
  marker.setCoordinates([
    Coordinates(latitude: 52.360495, longitude: 4.936882),
    Coordinates(latitude: 52.360495, longitude: 4.836882),
  ]);
  markerCollection.add(marker);

  _showMarkerCollectionOnMap(markerCollection);
}

// Method to draw and center on a polygon
void _onPolygonButtonPressed() {
  // Create a marker collection
  final markerCollection = MarkerCollection(
      markerType: MarkerType.polygon, name: 'Polygon marker collection');

  // Set coordinates of marker
  final marker = Marker();
  marker.setCoordinates([
    Coordinates(latitude: 52.340234, longitude: 4.886882),
    Coordinates(latitude: 52.300495, longitude: 4.936882),
    Coordinates(latitude: 52.300495, longitude: 4.836882),
  ]);
  markerCollection.add(marker);

  _showMarkerCollectionOnMap(markerCollection);
}

// Method to draw and center on points
void _onPointsButtonPressed() {
  // Create a marker collection
  final markerCollection = MarkerCollection(
      markerType: MarkerType.point, name: 'Points marker collection');

  // Set coordinates of marker
  final marker = Marker();
  marker.setCoordinates([
    Coordinates(latitude: 52.380495, longitude: 4.930882),
    Coordinates(latitude: 52.380495, longitude: 4.900882),
    Coordinates(latitude: 52.380495, longitude: 4.870882),
    Coordinates(latitude: 52.380495, longitude: 4.840882),
  ]);
  markerCollection.add(marker);

  _showMarkerCollectionOnMap(markerCollection);
}

This code snippet defines the methods to draw and display different shapes (polyline, polygon, points) on the map. Each method creates a MarkerCollection, adds markers with specific coordinates, and displays them on the map.

Utility Functions

void _showMarkerCollectionOnMap(MarkerCollection markerCollection) {
  final settings = MarkerCollectionRenderSettings();

  // Clear previous markers from the map
  _mapController.preferences.markers.clear();

  // Show the current marker on map and center on it
  _mapController.preferences.markers
      .add(markerCollection, settings: settings);
  _mapController.centerOnArea(markerCollection.area);
}

This utility method clears any previous markers on the map, then displays the new MarkerCollection and centers the map on the area containing the markers.

Flutter Examples

Maps SDK for Flutter Examples can be downloaded or cloned with Git