Android Google Map Custom Info Window Button Click Example

google map integration in android, android google map in fragment, android current location on google map, android google map custom marker, android google map custom info window

Android Google Map Custom Info Window Button Click Example is written here.

In this tutorial, I will explain how to create custom info window layout in google map.

Info window is something like a pop up rectangle that gives some information about the marker on google map.

It is mostly useful when you want to provide quick lines about the place. You can also provide an example image of the particular marker or place.

I will teach you how to hide this info window on the button click.

We will also consider how you can implement the button click of the info window on google map in android.

Output Of Info Window

Necessary Thing

Before you start making this example, you need to have google API Key.

This API key is necessary to integrate the google map in your android app.

For generating this API Key, you need to create one app in the Google Developer Console.

You should first read this Google Map API Integration in Android Example Tutorial for this purpose.

This tutorial has mainly two parts :

  1. Work At Google Developer Console (follow this part only)
  2. Work On Android Studio

You should follow all the steps of first part only. After this you will have your Google API Key. Now follow all the below steps to create info window on google map marker.

Step 1. Making New Activity

First of all, create a new project in the android studio.

In this process, you will be asked to choose activity type right after you entered project name, directory and SDK Version.

Following image shows to select default activity.

google map integration in android, android current location on google map, android google map custom marker, android google map custom info window
Select Google Map Activity
  • Here, select Google Maps Activity as your first activity.
  • Selecting Google Maps Activity will automatically enable the google map in your android app.

Step 2. Write API Key At Right Place

After creating project with Maps Activity, you will have one xml file called “google_maps_api.xml”

Compiler automatically creates this file at res->values directory.

Source Code for this file is as the following

<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=D7:DA:4B:AB:CB:75:20:AD:40:D6:AA:D8:31:E9:4B:E3:3A:33:36:30%3Bcom.example.parsaniahardik.googlemap_infowindow

    You can also add your credentials to an existing key, using these values:

    Package name:
    D7:DA:4B:AB:CB:75:20:AD:40:D6:AA:D8:31:E9:4B:E3:3A:33:36:30

    SHA-1 certificate fingerprint:
    D7:DA:4B:AB:CB:75:20:AD:40:D6:AA:D8:31:E9:4B:E3:3A:33:36:30

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">AIzaSy..YOUR API Key</string>
</resources>

As you can see in the above code, last lines holds the <string> </string> tags. Enter your Google API Key between these tags.

Step 3. Lion Image

As I have already said, we will add one image in our info window. So for this purpose, we have to add one image in the drawable folder.

Download a lion image by clicking the below link and copy it in drawable directory.

[sociallocker]Download a lion image[/sociallocker]

Step 4. Custom Layout For Info window

We need create one xml layout file. This file will work as a custom file for info window.

Info window will represent a layout generated by this file. So make a new xml layout file in res->layout directory.

Name of this file should be “gir_forest.xml.”

Add the below coding lines in “gir_forest.xml.”

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/lion"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvgir"
        android:textSize="20sp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:textColor="@color/colorAccent"
        android:text="Gir "/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvd"
        android:textSize="20sp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:textColor="@color/colorAccent"
        android:text="Gir "/>

</LinearLayout>
  • I have added one image view and two text views in the above file.
  • Image view represent the sample image of the place and two text views are providing basic information about the place or marker.

Step 5. Adapter class Info Window

Create a new Java class named “InfoWindowAdapter.java”

Copy the below code in it.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;

public class InfoWndowAdapter implements GoogleMap.InfoWindowAdapter {

    private Context context;

    public InfoWndowAdapter(Context context) {
        this.context = context.getApplicationContext();
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v =  inflater.inflate(R.layout.gir_forest, null);

        TextView tvGir = (TextView) v.findViewById(R.id.tvgir);
        TextView tvDetails = (TextView) v.findViewById(R.id.tvd);
       // TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);
        tvGir.setText("Gir Forest is located in the Gujarat State of India");
        tvDetails.setText("Forest is maily known for the Asiatic Lions.");
        //tvLng.setText("Longitude:"+ latLng.longitude);
        return v;
    }


}

This class provides data to text views. Object of this class will create display view for info window.

Step 6. Changing Default Activity

You have selected Map activity as a default activity in step 1. So you should have two files

First is activity_maps.xml and second one is MapsActivity.java

Write the below Source code in activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MapsActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Close All Infoviews"/>

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MapsActivity"/>

</LinearLayout>
  • One button and one fragment is present in the above code.
  • Compiler will load the google map in the fragment.
  • When the user will click the button, compiler will hide the info window.

Write down the following coding lines in MapsActivity.java

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener {

    private GoogleMap mMap;
    private Button btn;
    private Marker marker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    marker.hideInfoWindow();
            }
        });

        // 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.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng gir = new LatLng(21.169065, 70.596481);
        mMap.addMarker(new MarkerOptions().position(gir));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(gir));

        // Setting a custom info window adapter for the google map
        InfoWndowAdapter markerInfoWindowAdapter = new InfoWndowAdapter(getApplicationContext());
        googleMap.setInfoWindowAdapter(markerInfoWindowAdapter);

        // Adding and showing marker when the map is touched

                mMap.clear();
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(gir);
                mMap.animateCamera(CameraUpdateFactory.newLatLng(gir));
                marker = mMap.addMarker(markerOptions);
               // marker.showInfoWindow();

                googleMap.setOnInfoWindowClickListener(this);

            }

    @Override
    public void onInfoWindowClick(Marker marker) {
        Toast.makeText(this, "Gir Forest Clicked!!!!", Toast.LENGTH_SHORT).show();
    }
}

Attending the above code

Now let us one by one see what above code is doing.

  • First read the below code
  btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    marker.hideInfoWindow();
            }
        });
  • It is the code for button. Info window will be hidden when the user click the button.

See the below code

  // 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);
  • Compiler will start the process to create the google map with the help of the above code.

Following code is run when map is ready to be loaded in the fragment.

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

        // Add a marker in Sydney and move the camera
        LatLng gir = new LatLng(21.169065, 70.596481);
        mMap.addMarker(new MarkerOptions().position(gir));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(gir));

        // Setting a custom info window adapter for the google map
        InfoWndowAdapter markerInfoWindowAdapter = new InfoWndowAdapter(getApplicationContext());
        googleMap.setInfoWindowAdapter(markerInfoWindowAdapter);

        // Adding and showing marker when the map is touched

                mMap.clear();
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(gir);
                mMap.animateCamera(CameraUpdateFactory.newLatLng(gir));
                marker = mMap.addMarker(markerOptions);
               // marker.showInfoWindow();

                googleMap.setOnInfoWindowClickListener(this);

            }
  • Compiler will first add the marker in the map.
  • Then it will create an object of the InfoWindowAdapter class. After this, compiler will generate the info window with help of an object of the InfoWindowAdapter class.

Consider the below code

@Override
    public void onInfoWindowClick(Marker marker) {
        Toast.makeText(this, "Gir Forest Clicked!!!!", Toast.LENGTH_SHORT).show();
}
  • Above code will be run when the user click on the Info Window.

Related Map Tutorials

Following are useful tutorials for android google maps.

Download Source Code For Android Google Map Custom Info Window

[sociallocker]Download Source Code For GoogleMap InfoWindow[/sociallocker]