DEV Community

Cover image for Flutter Google Maps: Markers and Routes
Muhammad Uzair
Muhammad Uzair

Posted on Originally published at uzairxdev.online

Flutter Google Maps: Markers and Routes

Adding Google Maps to a Flutter app looks simple until the map stays blank, the markers never appear, or the blue dot refuses to show up. The google_maps_flutter plugin handles the rendering, but the setup around it — API keys, platform configuration, location permission, and the asynchronous map controller — is where most developers lose an afternoon. This guide walks through the full setup: API key, Android and iOS configuration, markers, polylines, and the user's current location, with working code at every step.

How do I add Google Maps to a Flutter app?

Add the google_maps_flutter package, put a Google Maps API key in the Android manifest and the iOS app delegate, enable the Maps SDK for Android and Maps SDK for iOS in Google Cloud Console, and render a GoogleMap widget with an initialCameraPosition. The map itself is one widget; the setup is the work. The plugin renders a native map view inside your Flutter widget tree, so the map behaves like a platform view, not a Flutter-drawn canvas. That matters for performance and for how you interact with it: you control the map through a GoogleMapController that arrives asynchronously in the onMapCreated callback.

Start by adding the dependency:

dependencies:
  flutter:
    sdk: flutter
  google_maps_flutter: ^2.9.0
Enter fullscreen mode Exit fullscreen mode

Then create a Google Cloud project, enable the Maps SDK for Android and the Maps SDK for iOS, and create an API key. Restrict the key in the Cloud Console: Android apps by package name and SHA-1 fingerprint, iOS apps by bundle identifier. An unrestricted key embedded in a shipped app can be extracted and used by anyone, so restriction is not optional for a production app.

On Android, add the key to android/app/src/main/AndroidManifest.xml, inside the <application> tag:

<meta-data
  android:name="com.google.android.geo.API_KEY"
  android:value="YOUR_API_KEY" />
Enter fullscreen mode Exit fullscreen mode

On iOS, open ios/Runner/AppDelegate.swift and provide the key before the Flutter engine starts:

import GoogleMaps

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR_API_KEY")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
Enter fullscreen mode Exit fullscreen mode

If the map renders as a blank grey grid, the cause is almost always one of three things: the API key is missing or wrong, the Maps SDK for that platform is not enabled, or the key is restricted to a different package name or bundle ID. Check the platform logs first — the native SDK prints a clear error for each of these.

How do I show a map with a starting position in Flutter?

Show a map in Flutter with the GoogleMap widget and an initialCameraPosition built from a LatLng and a zoom level. The camera position is the map's starting viewpoint: a target coordinate and a zoom value where 1 is the whole world and 20 is street level. A zoom of 14 to 15 works well for a neighbourhood view.

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

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

  @override
  State<MapScreen> createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  late GoogleMapController _controller;

  static const _initialPosition = CameraPosition(
    target: LatLng(33.6844, 73.0479),
    zoom: 14.0,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Map')),
      body: GoogleMap(
        initialCameraPosition: _initialPosition,
        onMapCreated: (controller) {
          _controller = controller;
        },
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

The GoogleMapController arrives in onMapCreated, so store it and use it only after that callback fires. Calling animateCamera before the controller exists is a common crash in first attempts. Keep a boolean flag or use a Completer<GoogleMapController> if other widgets need the controller before the map is ready.

How do I add markers to a Google Map in Flutter?

Add markers to a Google Map in Flutter by passing a Set<Marker> to the GoogleMap widget's markers property. Each marker needs a unique MarkerId and a position. The marker set is immutable from the widget's point of view: to add, move, or remove a marker, build a new set and call setState.

Set<Marker> _markers = {};

void _addMarker(LatLng position, String id, String title) {
  setState(() {
    _markers = {
      ..._markers,
      Marker(
        markerId: MarkerId(id),
        position: position,
        infoWindow: InfoWindow(title: title),
        onTap: () {
          debugPrint('Tapped marker $id');
        },
      ),
    };
  });
}
Enter fullscreen mode Exit fullscreen mode

Pass the set into the widget:

GoogleMap(
  initialCameraPosition: _initialPosition,
  onMapCreated: (controller) => _controller = controller,
  markers: _markers,
  onTap: (position) => _addMarker(position, 'pin-${position.latitude}', 'Dropped pin'),
)
Enter fullscreen mode Exit fullscreen mode

A marker with a duplicate MarkerId silently replaces the old one, which is actually useful: updating a marker's position is just adding a marker with the same ID and a new position. For a custom marker icon, load a BitmapDescriptor with BitmapDescriptor.fromAssetImage and pass it as the marker's icon. That call is asynchronous, so load the icon in initState and only add markers after it resolves. The default red pin is fine for a first version, and custom icons are a polish step, not a setup step.

How do I draw a route with polylines in Flutter?

Draw a route on a Google Map in Flutter with a Polyline in the GoogleMap widget's polylines property. A polyline is a list of LatLng points joined by a line, with a colour and a width in screen pixels. Like markers, polylines live in a set that you rebuild with setState when the route changes.

Set<Polyline> _polylines = {};

void _drawRoute(List<LatLng> points) {
  setState(() {
    _polylines = {
      Polyline(
        polylineId: const PolylineId('route'),
        points: points,
        color: Colors.blue,
        width: 5,
        startCap: Cap.roundCap,
        endCap: Cap.roundCap,
      ),
    };
  });
}
Enter fullscreen mode Exit fullscreen mode

In a real app the points come from a directions API, but the drawing step is the same whatever the source. When the route is ready, fit the whole route on screen by moving the camera to a LatLngBounds built from the points:

Future<void> _fitRoute(List<LatLng> points) async {
  final latitudes = points.map((p) => p.latitude);
  final longitudes = points.map((p) => p.longitude);
  final bounds = LatLngBounds(
    southwest: LatLng(
      latitudes.reduce((a, b) => a < b ? a : b),
      longitudes.reduce((a, b) => a < b ? a : b),
    ),
    northeast: LatLng(
      latitudes.reduce((a, b) => a > b ? a : b),
      longitudes.reduce((a, b) => a > b ? a : b),
    ),
  );
  await _controller.animateCamera(
    CameraUpdate.newLatLngBounds(bounds, 64),
  );
}
Enter fullscreen mode Exit fullscreen mode

Call newLatLngBounds only after the map has a size, or it throws: the map needs a laid-out size to compute the camera. In practice that means calling it from a button press or after a short delay following onMapCreated, not inside onMapCreated itself.

How do I show the users current location on a Google Map in Flutter?

Show the user's current location by requesting location permission with the geolocator package, reading the position, and moving the camera to it. The map's built-in blue dot (myLocationEnabled: true) shows where the device is, but it does not move the camera for you — you still need to fetch the position and animate the camera yourself.

Add the dependency and the platform permission entries. On Android, add to AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Enter fullscreen mode Exit fullscreen mode

On iOS, add a usage description to ios/Runner/Info.plist:

<key>NSLocationWhenInUseUsageDescription</key>
<string>Your location is used to centre the map and show nearby places.</string>
Enter fullscreen mode Exit fullscreen mode

Then request permission and read the position:

import 'package:geolocator/geolocator.dart';

Future<void> _goToCurrentLocation() async {
  LocationPermission permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
  }
  if (permission == LocationPermission.denied ||
      permission == LocationPermission.deniedForever) {
    debugPrint('Location permission denied');
    return;
  }

  final position = await Geolocator.getCurrentPosition();
  final current = LatLng(position.latitude, position.longitude);

  _addMarker(current, 'me', 'You are here');
  await _controller.animateCamera(
    CameraUpdate.newCameraPosition(
      CameraPosition(target: current, zoom: 16),
    ),
  );
}
Enter fullscreen mode Exit fullscreen mode

Handle the denied cases explicitly. deniedForever means the system will not show the permission dialog again, so the only recovery is sending the user to the app settings with Geolocator.openAppSettings(). A map screen that crashes or hangs on a denied permission is a common one-star review, so treat the denied path as a first-class state with a message and a retry button. Also check that location services are enabled with Geolocator.isLocationServiceEnabled() before requesting a position, and prompt the user to enable them with Geolocator.openLocationSettings() when they are off.

How do I keep a Flutter map screen fast and reliable?

Keep a Flutter map screen fast by treating the map as a native view with a small Flutter surface around it. The map itself renders natively and is cheap; the cost comes from rebuilding the widget tree around it. Keep markers and polylines in state outside the build method, rebuild only the sets that changed, and avoid putting the GoogleMap widget inside a widget that rebuilds on every frame, such as an animation listener.

A few rules that prevent the most common production bugs: dispose the GoogleMapController in dispose(); never call animateCamera before onMapCreated fires; load custom marker icons once in initState, not per build; and debounce map taps when a tap triggers a network call, such as reverse geocoding an address. Reverse geocoding every camera movement is a fast way to burn through a geocoding quota, so geocode on a settled tap or an explicit button instead.

For a deeper look at the same patterns in a shipped app, the Qibla Finder case study shows a compass and location-based feature built with the same permission and positioning flow, and the Ethiopian Calendar case study covers another app that leans on device state and careful platform setup. The Flutter geofencing guide covers the battery-friendly side of location work, and the Flutter local notifications guide pairs well with location reminders built on top of a map.

Conclusion

Google Maps in Flutter is three pieces: platform setup with a restricted API key, a GoogleMap widget driven by an asynchronously created controller, and sets of markers and polylines that you rebuild with setState. Get the key and the Maps SDK enablement right first, then add markers, then polylines, then the current location with a proper permission flow. Each piece is small on its own, and together they cover most map screens a production app needs.

Get in touch and let's talk about your project.


Originally published at uzairxdev.online

Top comments (0)