Android

Understanding Google Maps Marker In Android

create a map with pins
Written by Yasir Ameen

Google Maps Marker is very useful when you want to show the location pin on Google Maps. It is possible to use image or icon or bitmap as Google Maps Marker Icon, even you can customize it by creating a layout for custom marker . If you want to play with Google Map Marker then this tutorial is for you.

Let’s Start Creating Google Maps Marker

This tutorial assumes that you already know How to implement Google Maps, if you want to know how to implement Google Maps on your project then i will recommend you to first read How to Implement Google Maps

Download Source Code : https://github.com/YasirAmeen/GoogleMapsMarker

What I will cover

  1. Default Google Maps Marker
  2. Google Maps Marker With Icon
  3. Google Maps Marker With Bitmap
  4. Google Maps Marker With Multiple Pins
  5. Multiple Google Maps Marker With LatLng Bounds
  6. Google Maps With Custom Marker [Included Demo Video]

Understanding MarkerOptions Object

Well, MarkerOptions is a class which provide all the possible functionality for creating Google Map Marker of any type i mentioned above in a list. There are numbers of useful methods in MarkreOptions class which will help us to create marker on Google Map, have a look some useful and important methods of MarkerOptions class.

create google map with multiple pins

 

1) Creating Default Google Maps Marker

Creating default Google Maps Marker is very easy, just creat LatLng and MarkerOptions object and use addMarker() method of GoogleMap object for creating maker.



@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-33.8708488, 151.1879368);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(sydney, 15);
    mMap.animateCamera(update);
}


android google maps marker create a map with pins

2) Creating Google Maps Marker With Icon

You can show google maps pin with representation of image. The BitmapDescriptorFactory class provide various method that can help you to change an image of a Google maps marker from resources, assets, file etc etc.


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-33.8708488, 151.1879368);
    mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_icon)).position(sydney).title("Marker is near in Sydney"));
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(sydney, 13);
    mMap.animateCamera(update);
}

android google maps marker create map with pins

 

3) Creating Google Maps Marker With Bitmap

Implementing Bitmap as a Google maps pin is similar as described above, in the following code snippet, I am taking an image from the drawable resources and converting it into Bitmap. Sometimes we get Bitmap instead of image so we can use that Bitmap as a marker.


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    Drawable myDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.marker_icon, null);
    Bitmap markerBitmap = ((BitmapDrawable)myDrawable).getBitmap();

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-33.8708488, 151.1879368);
    mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(markerBitmap)).position(sydney).title("Marker is near in Sydney"));
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(sydney, 13);
    mMap.animateCamera(update);
}

google maps marker

4-5) Google Maps Marker With Multiple Pins

There are several reasons you map multiple locations on Google Maps. Let’s say you are receiving  a multiple locations as a List and you want to plot multiple markers. The List contains the Latitude and Longitude of the multiple locations. see the following code snippet.

LatLngBounds : I am using laglngbounds for showing all marker once on a mobile screen, well in easy way we set latlngbounds to zoom the Google Maps camera in that way that all markers may show on screen. It takes Point A as first latlng and takes Point B as last latlng of list of locations.

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    
    //When Map Loads Successfully
    mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
        @Override
        public void onMapLoaded() {
            //Your code where exception occurs goes here...
            List<LatLng> locations = new ArrayList<>();
            locations.add(new LatLng(24.821730,67.024680));
            locations.add(new LatLng(24.823327,67.028414));
            locations.add(new LatLng(24.823288,67.031568));
            locations.add(new LatLng(24.824677,67.033982));
            locations.add(new LatLng(24.823093,67.035559));
            locations.add(new LatLng(24.822489,67.036632));

            for(LatLng latLng : locations) {
                mMap.addMarker(new MarkerOptions().position(latLng).title("Title can be anything"));
            }

            //LatLngBound will cover all your marker on Google Maps
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(locations.get(0)); //Taking Point A (First LatLng)
            builder.include(locations.get(locations.size() - 1)); //Taking Point B (Second LatLng)
            LatLngBounds bounds = builder.build();
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 200);
            mMap.moveCamera(cu);
            mMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
        }
    });

}

google maps latlngbounds example android

6) Google Maps Custom Marker

This part is my favorite, you know can create custom marker 🙂 Yes just first create layout for custom marker in layout xml file and then convert the layout into bitmap, used BitmapDescriptorFactory.fromBitmap() method and pass the created bitmap from the layout. Let’s create it step by step.

Step 1) Create a custom layout for marker

Create a xml file in layout folder and name it custom_marker_layout.xml and paste the following code. I used three things here.

important: Please download the Source code in order to use above three things also dont forget to add circular image library

compile 'de.hdodenhof:circleimageview:2.1.0'

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/custom_marker_view"
    android:layout_width="52dp"
    android:layout_height="wrap_content">


    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/user_dp"
        android:layout_width="42dp"
        android:layout_height="46dp"
        app:civ_border_color="#fff"
        android:layout_alignParentTop="true"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="4dp"
        android:layout_marginTop="3.5dp"
        android:contentDescription="@null"
        android:src="@drawable/my_dp" />

    <RelativeLayout
        android:layout_width="50dp"
        android:layout_height="59dp"
        android:backgroundTint="#26c7db"
        android:background="@drawable/marker_image">

        <TextView
            android:text="janet John"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="7sp"
            android:layout_marginLeft="10dp"
            android:textColor="#000"
            android:alpha="0.8"
            android:background="@drawable/blur_circle"
            android:id="@+id/name"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />


    </RelativeLayout>


</RelativeLayout>

google maps custom marker example

Step 2) Writing a createCustomMarker Method

We will create a method that will convert our custom marker layout into Bitmap and BitmapDescriptorFactory.fromBitmap()  method will use converted bitmap to create custom marker for us.

public static Bitmap createCustomMarker(Context context, @DrawableRes int resource, String _name) {

    View marker = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null);

    CircleImageView markerImage = (CircleImageView) marker.findViewById(R.id.user_dp);
    markerImage.setImageResource(resource);
    TextView txt_name = (TextView)marker.findViewById(R.id.name);
    txt_name.setText(_name);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    marker.setLayoutParams(new ViewGroup.LayoutParams(52, ViewGroup.LayoutParams.WRAP_CONTENT));
    marker.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
    marker.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
    marker.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(marker.getMeasuredWidth(), marker.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    marker.draw(canvas);

    return bitmap;
}

Step 3) Plotting Customize Marker on  Google Maps

Now its time to plot customize marker on Map, Paste the following code in your onMapReady() function and run the app, but let me explain why creating custom marker is awesome, if you look the following code closely, you will see that i just created a function name createCustomMarker() and expecting an Image and Name as parameter so we can able to change image and text of every marker we want 🙂


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;


    //When Map Loads Successfully
    mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
        @Override
        public void onMapLoaded() {
            
            LatLng customMarkerLocationOne = new LatLng(24.823580, 67.025625);
            LatLng customMarkerLocationTwo = new LatLng(24.823229, 67.033070);
            LatLng customMarkerLocationThree = new LatLng(24.820211, 67.029465);


            mMap.addMarker(new MarkerOptions().position(customMarkerLocationOne).
                    icon(BitmapDescriptorFactory.fromBitmap(
                            createCustomMarker(MapsActivity.this,R.drawable.my_dp,"Yasir Ameen"))));
            mMap.addMarker(new MarkerOptions().position(customMarkerLocationTwo).
                    icon(BitmapDescriptorFactory.fromBitmap(
                            createCustomMarker(MapsActivity.this,R.drawable.janet,"Mary Jane"))));

            mMap.addMarker(new MarkerOptions().position(customMarkerLocationThree).
                    icon(BitmapDescriptorFactory.fromBitmap(
                            createCustomMarker(MapsActivity.this,R.drawable.john,"Janet John"))));

            //LatLngBound will cover all your marker on Google Maps
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(customMarkerLocationOne); //Taking Point A (First LatLng)
            builder.include(customMarkerLocationThree); //Taking Point B (Second LatLng)
            LatLngBounds bounds = builder.build();
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 200);
            mMap.moveCamera(cu);
            mMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
        }
    });


}

 

 

tell me about this tutorial in the comment below 🙂

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

3 Comments

Leave a Comment