Sitemap

Show Google Map with Marker in Flutter with GetX

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.

Press enter or click to view image in full size

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.

Get Shahadat Hossain Shaki’s stories in your inbox

Join Medium for free to get updates from this writer.

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.

--

--

Shahadat Hossain Shaki
Shahadat Hossain Shaki

Written by Shahadat Hossain Shaki

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