Flutter Flow: Google Maps Custom Marker Actions

Previously I discussed how to implement Custom Markers with and without Supabase on the Flutter Flow platform.
Flutter Flow: Use Supabase to show custom markers on Google Maps
Flutter Flow: Adding Custom Markers for Google Maps

Flutter Flow has made a lot of updates and improvements since then, including allowing you to pass Supabase Rows and Actions (callbacks).

I’m going to improve the previous code to make it more flexible and update page state with the Place Row whenever a custom marker is clicked. This results in a lot less code.

I am also submitting this code as a free template on the Flutter Flow Market Place.

Custom development

I get a lot of requests for custom tweaks of Google Maps with Flutter.

To better understand everyone’s needs, I have created a survey to capture these requests.

https://coffeebytez.substack.com/survey/639443

I will focus on the most highly requested items first, which will be available on my substack. I will also post exclusive in-depth tutorials there.

Please subscribe to my substack here:

https://coffeebytez.substack.com/?r=gdmkm&utm_campaign=pub-share-checklist

If you have urgent specific requests, please leave your contact information in the survey.

New Parameters

We have a few new parameters that will allow us to make the code more flexible and reusable across different pages and projects.

  • places — We will load the places table at a top level component of the page we include on the map.
  • **defaultZoom — **previously I set the default zoom at 11.0, I now have this as a parameter
  • onClickMarker — This is an action callback that returns the placeRow of the custom marker that was pressed

Note: The only nullable parameters are width, height, and onClickMarker. I have renamed lat > latitude and lng > longitude. I have also renamed Custom Widget to SupabaseMap. I may be better to click the duplicate widget button on your Custom Widget.

Also refer to the following article on adding the third party Google Map dependencies.
Flutter Flow: Adding Custom Markers for Google Maps

Improving The Code

Now let’s improve the code.

I’ll note a few improvements I made to this code.

  • We no longer use GoogleMapDataStruct.
  • Center is now a late initialized variable
  • Completely removed the loadData function.
  • Completely removed _fetchedMapData variable and replaced it with our places parameter.
  • Clicking on a map marker returns that markers placeRow object.
  • Added the ability to load network images (I’ve added this to the previous articles as well). For local asset images, you just give it the name like before. // Automatic FlutterFlow imports
    import ‘/backend/supabase/supabase.dart’;
    import ‘/flutter_flow/flutter_flow_theme.dart’;
    import ‘/flutter_flow/flutter_flow_util.dart’;
    import ‘/custom_code/widgets/index.dart’; // Imports other custom widgets
    import ‘/flutter_flow/custom_functions.dart’; // Imports custom functions
    import ‘package:flutter/material.dart’;
    // Begin custom widget code
    // DO NOT REMOVE OR MODIFY THE CODE ABOVE! import ‘package:google_maps_flutter/google_maps_flutter.dart’
    as google_maps_flutter;
    import ‘/flutter_flow/lat_lng.dart’ as latlng;
    import ‘dart:async’;
    export ‘dart:async’ show Completer;
    export ‘package:google_maps_flutter/google_maps_flutter.dart’ hide LatLng;
    export ‘/flutter_flow/lat_lng.dart’ show LatLng;
    import ‘package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart’;
    import ‘dart:ui’; class SupabaseMap extends StatefulWidget {
    const SupabaseMap({
    super.key,
    this.width,
    this.height,
    this.places,
    required this.centerLatitude,
    required this.centerLongitude,
    required this.showLocation,
    required this.showCompass,
    required this.showMapToolbar,
    required this.showTraffic,
    required this.allowZoom,
    required this.showZoomControls,
    required this.defaultZoom,
    this.onClickMarker,
    }); final double? width;
    final double? height;
    final List? places;
    final double centerLatitude;
    final double centerLongitude;
    final bool showLocation;
    final bool showCompass;
    final bool showMapToolbar;
    final bool showTraffic;
    final bool allowZoom;
    final bool showZoomControls;
    final double defaultZoom;
    final Future Function(PlaceRow? placeRow)? onClickMarker; @override
    State createState() => _SupabaseMapState();
    } class _SupabaseMapState extends State {
    Completer _controller = Completer();
    Map _customIcons = {};
    Set _markers = {}; late google_maps_flutter.LatLng _center; @override
    void initState() {
    super.initState(); _center = google_maps_flutter.LatLng( widget.centerLatitude, widget.centerLongitude); _loadMarkerIcons(); } Future _loadMarkerIcons() async {
    Set uniqueIconPaths =
    widget.places?.map((data) => data.imageUrl).toSet() ??
    {}; // Extract unique icon paths for (String? path in uniqueIconPaths) { if (path != null && path.isNotEmpty) { if (path.contains("https")) { Uint8List? imageData = await loadNetworkImage(path); if (imageData != null) { google_maps_flutter.BitmapDescriptor descriptor = await google_maps_flutter.BitmapDescriptor.fromBytes(imageData); _customIcons[path] = descriptor; } } else { google_maps_flutter.BitmapDescriptor descriptor = await google_maps_flutter.BitmapDescriptor.fromAssetImage( const ImageConfiguration(devicePixelRatio: 2.5), "assets/images/$path", ); _customIcons[path] = descriptor; } } } _updateMarkers(); // Update markers once icons are loaded } Future loadNetworkImage(String path) async {
    final completer = Completer();
    var image = NetworkImage(path);
    image.resolve(const ImageConfiguration()).addListener(ImageStreamListener(
    (ImageInfo info, bool _) => completer.complete(info)));
    final imageInfo = await completer.future;
    final byteData =
    await imageInfo.image.toByteData(format: ImageByteFormat.png);
    return byteData?.buffer.asUint8List();
    } void _updateMarkers() {
    setState(() {
    _markers = _createMarkers();
    });
    } void _onMapCreated(google_maps_flutter.GoogleMapController controller) {
    _controller.complete(controller);
    } Set _createMarkers() {
    var tmp = {};
    for (int i = 0; i < (widget.places ?? []).length; i++) {
    var place = widget.places?[i];
    final latlng.LatLng coordinates =
    latlng.LatLng(place?.latitude ?? 0.0, place?.longitude ?? 0.0);
    final google_maps_flutter.LatLng googleMapsLatLng =
    google_maps_flutter.LatLng(
    coordinates.latitude, coordinates.longitude);
    google_maps_flutter.BitmapDescriptor icon =
    _customIcons[place?.imageUrl] ??
    google_maps_flutter.BitmapDescriptor.defaultMarker; final google_maps_flutter.Marker marker = google_maps_flutter.Marker( markerId: google_maps_flutter.MarkerId('${place?.title ?? "Marker"}_$i'), // Use index to ensure uniqueness position: googleMapsLatLng, icon: icon, infoWindow: google_maps_flutter.InfoWindow( title: place?.title, snippet: place?.description), onTap: () async { final callback = widget.onClickMarker; if (callback != null) { await callback(place); } }, ); tmp.add(marker); } return tmp; } @override
    Widget build(BuildContext context) {
    return google_maps_flutter.GoogleMap(
    onMapCreated: _onMapCreated,
    zoomGesturesEnabled: widget.allowZoom,
    zoomControlsEnabled: widget.showZoomControls,
    myLocationEnabled: widget.showLocation,
    compassEnabled: widget.showCompass,
    mapToolbarEnabled: widget.showMapToolbar,
    trafficEnabled: widget.showTraffic,
    initialCameraPosition: google_maps_flutter.CameraPosition(
    target: _center,
    zoom: widget.defaultZoom,
    ),
    markers: _markers,
    );
    }
    }

Updating the Supabase place table

I’ve also made some small adjustments to the place table. Refer to the following article for the initial setup of Supabase.
Flutter Flow: Use Supabase to show custom markers on Google Maps

The changes are just renaming a few columns. You can keep them the same and just update the column names in the code above.

  • lat > latitude
  • lng > longitude
  • icon_path > image_url

Using our new Custom Widget

Let’s use our new custom Widget. On the page I want to use my map on go to the widget tree menu and click the top level widget.

Now go to the far right of Flutter Flow and click Add Query

Choose Supabase Query as the Query Type, choose your place table, add whatever filters you want, and click Confirm. I’m keeping it simple and choosing not to use filters for this demo.

Also click on State Management to create a Local Page State Variable. Remember in our custom Widget we created a parameter to return a placeRow for the customer Marker that was clicked. We will be storing it here.

Click on Add Field. Give the field a name such as selectedPlace of type Supabase Row. Also choose your table name, in my case place.

Find your custom Widget in the Widget Pallete.

I have a new project, so by default I have a column in my page. I dropped my custom widget here.

Now click on your custom Widget and update the parameters.

For the places parameter, you can click the orange icon setting and you will see place Rows. This is from our Supabase query we created earlier.

I also have defaultZoom and an action to set our page parameter when a custom marker is clicked. Click the Open button to create your action

Notice at the top of the popup it mentions it’s a callback. This simply means we are able to get an value back from any action. Click Add Action

Under State Management choose Update Page State

Click Add Field

Click our page state selectedPlace from the popup.

Set update type to Set Value

Click UNSET. Under callback parameters choose placeRow. This is our action parameter returned in from our custom Widget.

Close and save the action. For our custom Widget, under Padding & Alignment, I also chose Expanded .

Including Google Map API Key and local images for our Custom Widget

There are some minor limitations when using Google Maps and images in Flutter Flow. They won’t include the Google Map API key and local images if it does not see the Flutter Flow Google Map and Flutter Flow ImageView on any page.

In our case we might want to load a local asset image by specifying the name in the database.

To get around this create a blank page and drop Flutter Flows Google Map and ImageViews with the images you want to be included. You don’t have to have any navigation to these pages.

Test the custom Google Map with custom Markers

In my previous articles, at the time the custom Google Map wouldn’t render in Test Mode. With Flutter Flow’s latest updates it now loads our custom Google Map!

There is still one downside, the custom markers still don’t load in Test Mode. In all other modes it should work, I always download the project anyway.

What’s Next?

I am submitting this to the FlutterFlow marketplace for free, to make it easy for anyone to use without going through this process. I will add the link below.

If you want to get better at custom Flutter development I recommend this book (affiliate link)

Note: While the Custom Widget is in the approval process, you will not be able to add it to your projects.

https://marketplace.flutterflow.io/item/zeSFD2KlIXUOfcXYwi1e

Also we are not doing anything with the page state from the selected Marker. I plan to create another article to make use of this. Stay tuned!

I also will have a video of this same process so you can follow along that way if you choose.

Congratulations on implementing your new custom Google Map!

If you want to get better at custom Flutter development I recommend this book

Recommended Posts

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *