Show Google Map with Marker in Flutter with GetX

Shahadat Hossain Shaki
2 min readJul 31, 2023

Google map is one of the most common maps we use to show various place locations. Let's see how to set up a map with a marker.

First of all, Add Google map package to your project, In your “pubspec.yaml”

 google_maps_flutter: ^2.2.3

Now show the map

  showMap(Object item) {

Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

var markerIdVal = uniqueId;
final MarkerId markerId = MarkerId(markerIdVal);

// creating a new MARKER
final Marker marker = Marker(
markerId: markerId,
position: LatLng(
item.location.lat,
item.location.lng,
),
icon: controller.markerIcon.value, //We need to set icon in Getx controller
onTap: () {},
);

markers[markerId] = marker;

return Container(
height: 250,
width: double.infinity,
decoration: containerRoundShape(size: 16),
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: LatLng(item.location.lat, item.location.lng),
zoom: 15.5,
),

markers: Set<Marker>.of(markers.values),
zoomControlsEnabled: true,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
);
}

We need to set a custom maker icon inside the Getx controller. From generating marker icon from assets, you need to use await, so you can't use it while rendering the UI.

In Getx controller

  var markerIcon = BitmapDescriptor.defaultMarker.obs;


@override
void onInit() async {
initMarkerIcon();
super.onInit();
}

initMarkerIcon() async {
Uint8List? byts = await getBytesFromAsset('assets/icon/home_marker.png');
markerIcon.value = BitmapDescriptor.fromBytes(byts!);
markerIcon.refresh();
}

Future<Uint8List?> getBytesFromAsset(String path) async {
double pixelRatio = Get.mediaQuery.devicePixelRatio;
ByteData data = await rootBundle.load(path);
ui.Codec codec = await ui.instantiateImageCodec(
data.buffer.asUint8List(),
targetWidth: pixelRatio.round() * 40
);
ui.FrameInfo fi = await codec.getNextFrame();
return (await fi.image.toByteData(format: ui.ImageByteFormat.png))?.buffer.asUint8List();
}

All done. Happy coding.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shahadat Hossain Shaki
Shahadat Hossain Shaki

Written by Shahadat Hossain Shaki

Co-Founder and Android developer of Happihub. Loves to develop things.

No responses yet

Write a response