Google Maps is used in many apps for displaying a location and indicating a specific location on a map. We have seen the use of maps in many apps that provides services such as Ola, Uber, and many more. In these apps, you will get to see How we can add Custom Marker to Google Maps in Android.
What we are going to build in this article?
We will be building a simple application in which we will display a map and on that map, we will be displaying a custom marker on our app. Below is the screenshot in which we will get to see what we are going to do in this project. we are going to implement this project in both Java and Kotlin languages.
Implementation:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project.
Step 2: Generating an API key for using Google Maps
To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY. After adding this now we are ready for adding the custom marker to our app. After adding the API key, you can run your app and you will get to see a default marker on the Sydney location with the default marker.
Step 3: Adding a custom marker in Google Maps
For adding a custom marker to Google Maps navigate to the app > res > drawable > Right-Click on it > New > Vector Assets and select the icon which we have to show on your Map. You can change the color according to our requirements. After creating this icon now we will move towards adding this marker to our Map.
Step 4: Working with the MapsActivity.java file
Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
| importandroid.content.Context;importandroid.graphics.Bitmap;importandroid.graphics.Canvas;importandroid.graphics.drawable.Drawable;importandroid.os.Bundle;importandroidx.core.content.ContextCompat;importandroidx.fragment.app.FragmentActivity;importcom.google.android.gms.maps.CameraUpdateFactory;importcom.google.android.gms.maps.GoogleMap;importcom.google.android.gms.maps.OnMapReadyCallback;importcom.google.android.gms.maps.SupportMapFragment;importcom.google.android.gms.maps.model.BitmapDescriptor;importcom.google.android.gms.maps.model.BitmapDescriptorFactory;importcom.google.android.gms.maps.model.LatLng;importcom.google.android.gms.maps.model.MarkerOptions;publicclassMapsActivity    extendsFragmentActivity implementsOnMapReadyCallback {    privateGoogleMap mMap;    @Override    protectedvoidonCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_maps);        // Obtain the SupportMapFragment and get notified        // when the map is ready to be used.        SupportMapFragment mapFragment            = (SupportMapFragment)                  getSupportFragmentManager()                      .findFragmentById(R.id.map);        mapFragment.getMapAsync(this);    }    /**     * Manipulates the map once available.     * This callback is triggered when the map is ready to     * be used. This is where we can add markers or lines,     * add listeners or move the camera. In this case, we     * just add a marker near Sydney, Australia. If Google     * Play services is not installed on the device, the     * user will be prompted to install it inside the     * SupportMapFragment. This method will only be     * triggered once the user has installed Google Play     * services and returned to the app.     */    @OverridepublicvoidonMapReady(GoogleMap googleMap)    {        mMap = googleMap;        // Add a marker in Sydney and move the camera        LatLng sydney = newLatLng(-34, 151);        mMap.addMarker(newMarkerOptions()                           .position(sydney)                           .title("Marker in Sydney")                           // below line is use to add                           // custom marker on our map.                           .icon(BitmapFromVector(                               getApplicationContext(),                               R.drawable.ic_flag)));        mMap.moveCamera(            CameraUpdateFactory.newLatLng(sydney));    }    privateBitmapDescriptor    BitmapFromVector(Context context, intvectorResId)    {        // below line is use to generate a drawable.        Drawable vectorDrawable = ContextCompat.getDrawable(            context, vectorResId);        // below line is use to set bounds to our vector        // drawable.        vectorDrawable.setBounds(            0, 0, vectorDrawable.getIntrinsicWidth(),            vectorDrawable.getIntrinsicHeight());        // below line is use to create a bitmap for our        // drawable which we have added.        Bitmap bitmap = Bitmap.createBitmap(            vectorDrawable.getIntrinsicWidth(),            vectorDrawable.getIntrinsicHeight(),            Bitmap.Config.ARGB_8888);        // below line is use to add bitmap in our canvas.        Canvas canvas = newCanvas(bitmap);        // below line is use to draw our        // vector drawable in canvas.        vectorDrawable.draw(canvas);        // after generating our bitmap we are returning our        // bitmap.        returnBitmapDescriptorFactory.fromBitmap(bitmap);    }} | 
Kotlin
| packagecom.example.map_custonm_markerimportandroid.content.Contextimportandroid.graphics.Bitmapimportandroid.graphics.Canvasimportandroid.graphics.drawable.Drawableimportandroidx.appcompat.app.AppCompatActivityimportandroid.os.Bundleimportandroidx.core.content.ContextCompat// Importing maps librariesimportcom.google.android.gms.maps.CameraUpdateFactoryimportcom.google.android.gms.maps.GoogleMapimportcom.google.android.gms.maps.OnMapReadyCallbackimportcom.google.android.gms.maps.SupportMapFragmentimportcom.google.android.gms.maps.model.LatLngimportcom.google.android.gms.maps.model.MarkerOptionsimportcom.example.map_custonm_marker.databinding.ActivityMapsBindingimportcom.google.android.gms.maps.model.BitmapDescriptorimportcom.google.android.gms.maps.model.BitmapDescriptorFactory// classclassMapsActivity : AppCompatActivity(), OnMapReadyCallback {    privatelateinit var mMap: GoogleMap    privatelateinit var binding: ActivityMapsBinding    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        binding = ActivityMapsBinding.inflate(layoutInflater)        setContentView(binding.root)        // Obtain the SupportMapFragment and get notified when the map is ready to be used.        val mapFragment = supportFragmentManager            .findFragmentById(R.id.map) as SupportMapFragment        mapFragment.getMapAsync(this)    }    override fun onMapReady(googleMap: GoogleMap) {        mMap = googleMap        // Add a marker in Sydney and move the camera        val sydney = LatLng(-34.0, 151.0)        val marker=MarkerOptions().position(sydney).title("Marker in Sydney")        //set custom icon        marker.icon(BitmapFromVector(getApplicationContext(), R.drawable.baseline_flag_24))        //add marker        mMap.addMarker(marker)        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))    }   privatefun BitmapFromVector(context:Context,vectorResId:Int): BitmapDescriptor? {       //drawable generator       var vectorDrawable: Drawable       vectorDrawable= ContextCompat.getDrawable(context,vectorResId)!!       vectorDrawable.setBounds(0,0,vectorDrawable.intrinsicWidth,vectorDrawable.intrinsicHeight)       //bitmap genarator       var bitmap:Bitmap       bitmap= Bitmap.createBitmap(vectorDrawable.intrinsicWidth,vectorDrawable.intrinsicHeight,Bitmap.Config.ARGB_8888)       //canvas genaret       var canvas:Canvas       //pass bitmap in canvas constructor       canvas= Canvas(bitmap)       //pass canvas in drawable       vectorDrawable.draw(canvas)        //return BitmapDescriptorFactory       returnBitmapDescriptorFactory.fromBitmap(bitmap)   }} | 
Now run your app and see the output of the app.
Output:
Note: In the Google Developer Console (https://console.developers.google.com), ensure that the “Google Maps Android API v2” is enabled. And also ensure that your API Key exists.

 
                                    








