AutoComplete Search bar in Google Maps

前端 未结 2 1985
悲&欢浪女
悲&欢浪女 2020-12-10 16:23

I\'m creating an app based on places search. I would like to know how can I add a search bar into my Google Map, where the user can select a Place, and I can capture what th

2条回答
  •  感动是毒
    2020-12-10 17:02

    You can simply use a PlaceAutoCompleteFragment.

    First ensure that you're using the latest version of Google Play Services (Version 8.4.0 and up includes the PlaceAutoCompleteFragment class):

    compile 'com.google.android.gms:play-services-maps:11.0.2'
    compile 'com.google.android.gms:play-services-location:11.0.2'
    compile 'com.google.android.gms:play-services-places:11.0.2'
    

    Then include the PlaceAutoCompleteFragment in your xml layout:

    
    
        
    
        
    
    
    
    

    Then set up a listener in your Activity:

    import com.google.android.gms.common.api.Status;
    import com.google.android.gms.location.places.Place;
    import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
    import com.google.android.gms.location.places.ui.PlaceSelectionListener;
    
    public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
    
        private GoogleMap mMap;
        PlaceAutocompleteFragment placeAutoComplete;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
    
            placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
            placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
                @Override
                public void onPlaceSelected(Place place) {
    
                    Log.d("Maps", "Place selected: " + place.getName());
                }
    
                @Override
                public void onError(Status status) {
                    Log.d("Maps", "An error occurred: " + status);
                }
            });
    
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
        }
    }
    

    When you run this code, you'll see the AutoComplete bar above the Google Map:

    When you click on the AutoComplete bar, it will look like this:

    Then, start typing, and select a Place:

    When you tap on a place to select it, you will see the log from the PlaceSelectionListener:

    D/Maps: Place selected: San Francisco
    

提交回复
热议问题