Skip to content
Related Articles

Related Articles

How to Add OnClickListner to Marker on Google Maps in Android?
  • Last Updated : 26 Jan, 2021
GeeksforGeeks - Summer Carnival Banner

We have seen implementing Marker on Google Maps in Android. Now we will see adding OnClickListner for that marker on our Google Maps. In this article, we will take a look at adding OnClickListner to Google Maps marker in Android. 

What we are going to build in this article? 

We will be building a simple application in which we will be showing a marker on a specific location on a map and we will be adding OnClickListner to the marker on Google Maps. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Add OnClickListner to Marker on Google Maps in Android Sample GIF

Step by Step 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

Step 3: Adding OnClickListner to Marker in Google Maps

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




import android.os.Bundle;
import android.widget.Toast;
  
import androidx.fragment.app.FragmentActivity;
  
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;
  
import java.util.ArrayList;
  
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
  
    private GoogleMap mMap;
      
    // below are the latitude and longitude
    // of 4 different locations.
    LatLng sydney = new LatLng(-34, 151);
    LatLng TamWorth = new LatLng(-31.083332, 150.916672);
    LatLng NewCastle = new LatLng(-32.916668, 151.750000);
    LatLng Brisbane = new LatLng(-27.470125, 153.021072);
      
    // two array list for our lat long and location Name;
    private ArrayList<LatLng> latLngArrayList;
    private ArrayList<String> locationNameArraylist;
  
    @Override
    protected void onCreate(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);
          
        // initializing our array lists.
        latLngArrayList = new ArrayList<>();
        locationNameArraylist = new ArrayList<>();
          
        // on below line we are adding
        // data to our array list.
        latLngArrayList.add(sydney);
        locationNameArraylist.add("Sydney");
        latLngArrayList.add(TamWorth);
        locationNameArraylist.add("TamWorth");
        latLngArrayList.add(NewCastle);
        locationNameArraylist.add("New Castle");
        latLngArrayList.add(Brisbane);
        locationNameArraylist.add("Brisbase");
    }
  
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
          
        // below line is to add marker to google maps
        for (int i = 0; i < latLngArrayList.size(); i++) {
             
            // adding marker to each location on google maps
            mMap.addMarker(new MarkerOptions().position(latLngArrayList.get(i)).title("Marker in " + locationNameArraylist.get(i)));
             
            // below line is use to move camera.
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        }
          
        // adding on click listener to marker of google maps.
        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                // on marker click we are getting the title of our marker 
                // which is clicked and displaying it in a toast message.
                String markerName = marker.getTitle();
                Toast.makeText(MapsActivity.this, "Clicked location is " + markerName, Toast.LENGTH_SHORT).show();
                return false;
            }
        });
    }
}

After adding this code. 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.

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :