Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaHow to Add SearchView in Google Maps in Android?

How to Add SearchView in Google Maps in Android?

We have seen the implementation of Google Maps in Android along with markers on it. But many apps provide features so that users can specify the location on which they have to place markers. So in this article, we will implement a SearchView in our Android app so that we can search a location name and add a marker to that location. 

What we are going to build in this article? 

We will be building a simple application in which we will be displaying a simple Google map and a SearchView. Inside that search view when users enter any location name then we will add a marker to that location on Google Maps. A sample video 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. 

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: Working with the activity_maps.xml file

As we are adding SearchView to our Google Maps for searching a location and adding a marker on that location. So we have to add a search view to our activity_maps.xml file. For adding SearchView, navigate to the app > res > layout > activity_maps.xml and add the below code to it. Comments are added in the code to get to know in more detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <!--fragment to display our maps-->
    <fragment xmlns:tools="http://schemas.android.com/tools"
        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" />
  
    <!--search view to search our location-->
    <androidx.appcompat.widget.SearchView
        android:id="@+id/idSearchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="#BFBFBF"
        android:elevation="5dp"
        app:iconifiedByDefault="false"
        app:queryHint="Search Here" />
  
</RelativeLayout>


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




import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
  
import androidx.appcompat.widget.SearchView;
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.MarkerOptions;
  
import java.io.IOException;
import java.util.List;
  
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
  
    private GoogleMap mMap;
      
    // creating a variable 
    // for search view.
    SearchView searchView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
          
        // initializing our search view.
        searchView = findViewById(R.id.idSearchView);
          
        // Obtain the SupportMapFragment and get notified 
        // when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
          
        // adding on query listener for our search view.
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // on below line we are getting the 
                // location name from search view.
                String location = searchView.getQuery().toString();
                  
                // below line is to create a list of address
                // where we will store the list of all address.
                List<Address> addressList = null;
                  
                // checking if the entered location is null or not.
                if (location != null || location.equals("")) {
                    // on below line we are creating and initializing a geo coder.
                    Geocoder geocoder = new Geocoder(MapsActivity.this);
                    try {
                        // on below line we are getting location from the 
                        // location name and adding that location to address list.
                        addressList = geocoder.getFromLocationName(location, 1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // on below line we are getting the location 
                    // from our list a first position.
                    Address address = addressList.get(0);
                      
                    // on below line we are creating a variable for our location
                    // where we will add our locations latitude and longitude.
                    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                      
                    // on below line we are adding marker to that position.
                    mMap.addMarker(new MarkerOptions().position(latLng).title(location));
                      
                    // below line is to animate camera to that position.
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
                }
                return false;
            }
  
            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        // at last we calling our map fragment to update.
        mapFragment.getMapAsync(this);
    }
      
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    }
}


Now run your app and see the output of the app. 

Output:

RELATED ARTICLES

Most Popular

Recent Comments