Flutter Flow: Google Maps Custom Marker Actions

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.

I have created a form to better understand everyone’s needs. You can also request custom Flutter Flow development and/or Flutter Flow training.

https://coffeebytez.com/contact-me/

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.
........

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<PlaceRow>? 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<SupabaseMap> createState() => _SupabaseMapState();
}

class _SupabaseMapState extends State<SupabaseMap> {
  Completer<google_maps_flutter.GoogleMapController> _controller = Completer();
  Map<String, google_maps_flutter.BitmapDescriptor> _customIcons = {};
  Set<google_maps_flutter.Marker> _markers = {};

  late google_maps_flutter.LatLng _center;

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

    _center = google_maps_flutter.LatLng(
        widget.centerLatitude, widget.centerLongitude);

    _loadMarkerIcons();
  }

  @override
  void didUpdateWidget(SupabaseMap oldWidget) {   
      super.didUpdateWidget(oldWidget);  
      if (oldWidget.places != widget.places) { 
          _loadMarkerIcons();   
      }  
  }

  Future<void> _loadMarkerIcons() async {
    Set<String?> 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
  }


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


  Set<google_maps_flutter.Marker> _createMarkers() {
    var tmp = <google_maps_flutter.Marker>{};
    for (int i = 0; i < (widget.places ?? []).length; i++) {
      var place = widget.places?[i];
     
      final google_maps_flutter.LatLng googleMapsLatLng =
          google_maps_flutter.LatLng(
              place?.latitude ?? 0.0, place?.longitude ?? 0.0);

      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,
    );
  }
}

Get the full code here:

Flutter Flow Custom Marker Actions

Updating he 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.

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.

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.

Now click Add Query

Choose Supabase Query as the Query Type, choose your place table, add whatever filters you want, and click Confirm. Also dont forget to create an Action Output variable name such as supabaseList. I’m keeping it simple and choosing not to use filters for this demo.

Add another action to the backend call to update the supabaseItems Page State with the supabaseList Action Output variable

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. Notice we are using the page state variable supabaseItems for the places parameter.

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