我正在使用PlaceAutocompleteFragment作为当前位置和目的地位置。但是我无法像Uber一样实现方向搜索。有人帮我吗?
PlaceAutocompleteFragment originAutocomplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.origin_autocomplete_fragment);
//AutocompleteFilter typeFilter = new AutocompleteFilter.Builder().setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES).build();
//originAutocomplete.setFilter(typeFilter);
originAutocomplete.setHint("Current Location");
originAutocomplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
Log.d(TAG, "Place selected: " + place.getName());
}
@Override
public void onError(Status status) {
Log.d(TAG, "An error occurred: " + status);
}
});
PlaceAutocompleteFragment destinationAutocomplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.destination_autocomplete_fragment);
destinationAutocomplete.setHint("Search Destination");
destinationAutocomplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
Log.d(TAG, "Place selected: " + place.getName());
}
@Override
public void onError(Status status) {
Log.d(TAG, "An error occurred: " + status);
}
});
答案 0 :(得分:0)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_marginTop="70dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:hint="Enter Place Here"
android:textColorHint="#BDBDBD"
android:drawableRight="@drawable/ic_search_black_24dp"
android:popupBackground="@android:color/white"
android:background="@color/colorWhite"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView2"
android:layout_below="@+id/autoCompleteTextView1"
android:layout_marginTop="2dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:hint="Enter Place Here"
android:textColorHint="#BDBDBD"
android:drawableRight="@drawable/ic_search_black_24dp"
android:popupBackground="@android:color/white"
android:background="@color/colorWhite"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
package com.eride.rider;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;
import com.eride.rider.utility.PlaceArrayAdapter;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
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.MarkerOptions;
public class Main2Activity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private static final String TAG = "Main2Activity";
private GoogleMap mMap;
private static final int GOOGLE_API_CLIENT_ID = 0;
private AutoCompleteTextView mAutocompleteTextView, mAutocompleteTextView2;
private GoogleApiClient mGoogleApiClient;
private PlaceArrayAdapter mPlaceArrayAdapter;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(new LatLng(20.86382, 88.15638), new LatLng(26.33338, 92.30153));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mAutocompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
mAutocompleteTextView2 = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
mGoogleApiClient = new GoogleApiClient.Builder(Main2Activity.this)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.addConnectionCallbacks(this)
.build();
mPlaceArrayAdapter = new PlaceArrayAdapter(this, android.R.layout.simple_list_item_1, BOUNDS_MOUNTAIN_VIEW, null);
mAutocompleteTextView.setAdapter(mPlaceArrayAdapter);
mAutocompleteTextView2.setAdapter(mPlaceArrayAdapter);
//http://kvenkataprasad.blogspot.com/2017/03/autocomplete-google-places-api-example.html
mAutocompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mGoogleApiClient, String.valueOf(mPlaceArrayAdapter.getItem(position).placeId));
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(@NonNull PlaceBuffer places) {
if (places.getStatus().isSuccess()) {
Log.d(TAG, "Address1: " + places.get(0).getAddress());
Log.d(TAG, "LatLng1: " + places.get(0).getLatLng().latitude +", "+ places.get(0).getLatLng().longitude);
}
}
});
}
});
mAutocompleteTextView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mGoogleApiClient, String.valueOf(mPlaceArrayAdapter.getItem(position).placeId));
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(@NonNull PlaceBuffer places) {
if (places.getStatus().isSuccess()) {
Log.d(TAG, "Address2: " + places.get(0).getAddress());
Log.d(TAG, "LatLng2: " + places.get(0).getLatLng().latitude +", "+ places.get(0).getLatLng().longitude);
}
}
});
}
});
}
@Override public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(23.793740, 90.388078);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
addMapMarker(latLng);
//locationButtonClicked();
}
private void addMapMarker(LatLng latLng) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mPlaceArrayAdapter.setGoogleApiClient(mGoogleApiClient);
Log.d(TAG, "Google Places API connected.");
}
@Override
public void onConnectionSuspended(int i) {
mPlaceArrayAdapter.setGoogleApiClient(null);
Log.d(TAG, "Google Places API connection suspended.");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "Google Places API connection failed with error code: " + connectionResult.getErrorCode());
Toast.makeText(this, "Google Places API connection failed with error code:" + connectionResult.getErrorCode(), Toast.LENGTH_LONG).show();
}
}
package com.eride.rider.utility;
import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLngBounds;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
public class PlaceArrayAdapter extends ArrayAdapter<PlaceArrayAdapter.PlaceAutocomplete> implements Filterable {
private static final String TAG = "PlaceArrayAdapter";
private GoogleApiClient mGoogleApiClient;
private AutocompleteFilter mPlaceFilter;
private LatLngBounds mBounds;
private ArrayList<PlaceAutocomplete> mResultList;
public PlaceArrayAdapter(Context context, int resource, LatLngBounds bounds, AutocompleteFilter filter) {
super(context, resource);
mBounds = bounds;
mPlaceFilter = filter;
}
public void setGoogleApiClient(GoogleApiClient googleApiClient) {
if (googleApiClient == null || !googleApiClient.isConnected()) {
mGoogleApiClient = null;
} else {
mGoogleApiClient = googleApiClient;
}
}
@Override
public int getCount() {
return mResultList.size();
}
@Override
public PlaceAutocomplete getItem(int position) {
return mResultList.get(position);
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null) {
mResultList = getPredictions(constraint);
if (mResultList != null) {
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
notifyDataSetInvalidated();
}
}
};
return filter;
}
private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) {
if (mGoogleApiClient != null) {
Log.i(TAG, "Executing autocomplete query for: " + constraint);
PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, constraint.toString(), mBounds, mPlaceFilter);
// Wait for predictions, set the timeout.
AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(getContext(), "Error: " + status.toString(), Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting place predictions: " + status.toString());
autocompletePredictions.release();
return null;
}
Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount() + " predictions.");
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getFullText(null)));
}
// Buffer release
autocompletePredictions.release();
return resultList;
}
Log.e(TAG, "Google API client is not connected.");
return null;
}
public class PlaceAutocomplete {
public CharSequence placeId;
public CharSequence description;
PlaceAutocomplete(CharSequence placeId, CharSequence description) {
this.placeId = placeId;
this.description = description;
}
@Override
public String toString() {
return description.toString();
}
}
}