📜  如何在Android的Google Maps中添加SearchView?

📅  最后修改于: 2021-05-13 17:55:49             🧑  作者: Mango

我们已经看到了Android中Google Maps的实现以及其上的标记。但是许多应用程序提供了功能,以便用户可以指定必须放置标记的位置。因此,在本文中,我们将在Android应用中实现SearchView,以便我们可以搜索位置名称并将标记添加到该位置。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,其中将显示一个简单的Google地图和一个SearchView 。当用户输入任何位置名称时,在该搜索视图内,我们将在Google Maps上向该位置添加一个标记。下面提供了一个示例视频,以使您对我们在本文中将要做的事情有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。确保在创建新项目时选择“地图活动”。

第2步:生成用于使用Google Maps的API密钥

要生成Maps的API密钥,您可以参考 如何生成在Android中使用Google Maps的API密钥。生成Google Maps的API密钥后。我们必须将此密钥添加到我们的项目中。要在我们的应用程序中添加此密钥,请导航至values文件夹> google_maps_api.xml文件,并在第23行中,您必须在YOUR_API_KEY位置添加API密钥。

步骤3:使用activity_maps.xml文件

当我们将SearchView添加到我们的Google Maps中以搜索位置并在该位置上添加标记时。因此,我们必须将搜索视图添加到我们的activity_maps.xml文件中。要添加SearchView,请导航至应用程序> res>布局> activity_maps.xml,然后将以下代码添加到其中。在代码中添加了注释,以便更详细地了解。

XML


  
    
    
  
    
    
  


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
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;     } }


步骤4:使用MapsActivity。 Java文件

转到MapsActivity。 Java文件并参考以下代码。以下是MapsActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

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
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;     } }

现在运行您的应用程序,并查看该应用程序的输出。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!