How to Add Custom Markers on Google Maps in Flutter?
Last Updated :
01 Aug, 2022
Google Maps is one of the popular apps used nowadays for navigation or locating markers on Google Maps. We have seen markers on Google Maps for various locations. But In this article, we are going to see how to implement multiple custom markers on Google Maps in Flutter.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Generating API Key for Using Google Maps
Check out the below article on How to generate an API key for using Google Maps. After developing that key we have to use it within our project to integrate Google Maps.
Now, follow the Steps to Implement Google Maps in the Flutter Application
Step 3: Adding Dependency to pubspec.yaml File
dependencies:
flutter:
google_maps_flutter: ^2.1.8
Now click on pub.get to configure.
Step 4: Update build.gradle File
Navigate to android>app>build.gradle file and update code on below line.
Change Compile SDK Version
android {
compileSdkVersion 31
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Change Min SDK Version
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.google_maps"
minSdkVersion 20
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
Step 5: Add API Key to Android Manifest File
Navigate to android > app > src > main > AndrodManifest.xml file and add the below code in the manifest tag. Make sure to add your Google Maps API key in the value.
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="Enter your API key here"/>
Step 6: Add Images in pubspec.yaml File for displaying Custom Markers
Add images in the assets folder in pubspec.yaml file
# To add assets to your application, add an assets section, like this
assets:
- images/bus.png
- images/car.png
- images/travelling.png
- images/bycicle.png
- images/food-delivery.png
Step 7: Working with main.dart File
Navigate to lib > main.dart file and add the below code to it. Comments are added in the code to get to know in detail.
Dart
import 'package:flutter/material.dart';
import 'package:google_maps/Convert_Lat_Long.dart';
import 'package:google_maps/HomePage.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GFG',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.green,
),
// First screen of our app
home: const HomePage(),
);
}
}
Step 8: Creating a new Dart File for Home Page
Navigate to lib > Right click on it > New > Dart File and name it as HomePage.dart. After creating that file add the below code to it. Comments are added in the code to get to know in detail.
Dart
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// created controller for displaying Google Maps
Completer<GoogleMapController> _controller = Completer();
// given camera position
static final CameraPosition _kGoogle = const CameraPosition(
target: LatLng(19.0759837, 72.8776559),
zoom: 15,
);
Uint8List? marketimages;
List<String> images = ['images/car.png','images/bus.png', 'images/travelling.png', 'images/bycicle.png', 'images/food-delivery.png'];
// created empty list of markers
final List<Marker> _markers = <Marker>[];
// created list of coordinates of various locations
final List<LatLng> _latLen = <LatLng>[
LatLng(19.0759837, 72.8776559),
LatLng(28.679079, 77.069710),
LatLng(26.850000, 80.949997),
LatLng(24.879999, 74.629997),
LatLng(16.166700, 74.833298),
LatLng(12.971599, 77.594563),
];
// declared method to get Images
Future<Uint8List> getImages(String path, int width) async{
ByteData data = await rootBundle.load(path);
ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(), targetHeight: width);
ui.FrameInfo fi = await codec.getNextFrame();
return(await fi.image.toByteData(format: ui.ImageByteFormat.png))!.buffer.asUint8List();
}
@override
void initState() {
// TODO: implement initState
super.initState();
// initialize loadData method
loadData();
}
// created method for displaying custom markers according to index
loadData() async{
for(int i=0 ;i<images.length; i++){
final Uint8List markIcons = await getImages(images[i], 100);
// makers added according to index
_markers.add(
Marker(
// given marker id
markerId: MarkerId(i.toString()),
// given marker icon
icon: BitmapDescriptor.fromBytes(markIcons),
// given position
position: _latLen[i],
infoWindow: InfoWindow(
// given title for marker
title: 'Location: '+i.toString(),
),
)
);
setState(() {
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF0F9D58),
// on below line we have given title of app
title: Text("GFG"),
),
body: Container(
child: SafeArea(
child: GoogleMap(
// given camera position
initialCameraPosition: _kGoogle,
// set markers on google map
markers: Set<Marker>.of(_markers),
// on below line we have given map type
mapType: MapType.normal,
// on below line we have enabled location
myLocationEnabled: true,
myLocationButtonEnabled: true,
// on below line we have enabled compass
compassEnabled: true,
// below line displays google map in our app
onMapCreated: (GoogleMapController controller){
_controller.complete(controller);
},
),
),
),
);
}
}
Output:
Similar Reads
Architecture of 8085 microprocessor A microprocessor is fabricated on a single integrated circuit (IC) or chip that is used as a central processing unit (CPU).The 8085 microprocessor is an 8-bit microprocessor that was developed by Intel in the mid-1970s. It was widely used in the early days of personal computing and was a popular cho
11 min read
Android Architecture Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
States of a Process in Operating Systems In an operating system, a process is a program that is being executed. During its execution, a process goes through different states. Understanding these states helps us see how the operating system manages processes, ensuring that the computer runs efficiently. Please refer Process in Operating Sys
11 min read
Flutter Tutorial This Flutter Tutorial is specifically designed for beginners and experienced professionals. It covers both the basics and advanced concepts of the Flutter framework.Flutter is Googleâs mobile SDK that builds native Android and iOS apps from a single codebase. It was developed in December 2017. When
7 min read
Android Tutorial In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor
15+ min read
Dart Tutorial Dart is an open-source general-purpose programming language developed by Google. It supports application development on both the client and server side. However, it is widely used for the development of Android apps, iOS apps, IoT(Internet of Things), and web applications using the Flutter Framework
7 min read
Activity Lifecycle in Android with Demo App In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when
9 min read
Introduction to Android Development Android operating system is the largest installed base among various mobile platforms across the globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It conquered around 71% of the global market share by the end of 2021, and this trend is grow
5 min read
Android UI Layouts Layouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip
5 min read
Top 50 Android Interview Questions and Answers - SDE I to SDE III A Linux-based open-source OS, Android was created by Andy Rubin and became one of the most popular smartphone operating systems. With 71 percent of the market share worldwide, Android is on top. Because it is on top in the smartphone OS, Android development is always in demand.If you are seeking a j
15+ min read