Java Android谷歌地点:不返回所选地点
在这里学习了教程。 但是,当在搜索栏中搜索某个内容时,从建议中选择一个,然后按“拾取位置”按钮,地图将显示用户的当前位置,而不是他/她选择的位置。有人能提供解决方案吗 MainActivity.javaJava Android谷歌地点:不返回所选地点,java,android,google-places-api,Java,Android,Google Places Api,在这里学习了教程。 但是,当在搜索栏中搜索某个内容时,从建议中选择一个,然后按“拾取位置”按钮,地图将显示用户的当前位置,而不是他/她选择的位置。有人能提供解决方案吗 MainActivity.java public class MainActivity extends AppCompatActivity { private PlacePicker.IntentBuilder builder; private PlacesAutoCompleteAdapter mPlacesAdapter;
public class MainActivity extends AppCompatActivity {
private PlacePicker.IntentBuilder builder;
private PlacesAutoCompleteAdapter mPlacesAdapter;
private Button pickerBtn;
private AutoCompleteTextView myLocation;
private static final int PLACE_PICKER_FLAG = 1;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
protected GoogleApiClient mGoogleApiClient;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Places.GEO_DATA_API)
.build();
setContentView(R.layout.activity_main);
builder = new PlacePicker.IntentBuilder();
myLocation = (AutoCompleteTextView) findViewById(R.id.myLocation);
mPlacesAdapter = new PlacesAutoCompleteAdapter(this, android.R.layout.simple_list_item_1,
mGoogleApiClient, BOUNDS_GREATER_SYDNEY, null);
myLocation.setOnItemClickListener(mAutocompleteClickListener);
myLocation.setAdapter(mPlacesAdapter);
pickerBtn = (Button) findViewById(R.id.pickerBtn);
pickerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
builder = new PlacePicker.IntentBuilder();
Intent intent = builder.build(MainActivity.this);
// Start the Intent by requesting a result, identified by a request code.
startActivityForResult(intent, PLACE_PICKER_FLAG);
} catch (GooglePlayServicesRepairableException e) {
GooglePlayServicesUtil
.getErrorDialog(e.getConnectionStatusCode(), MainActivity.this, 0);
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(MainActivity.this, "Google Play Services is not available.",
Toast.LENGTH_LONG)
.show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PLACE_PICKER_FLAG:
Place place = PlacePicker.getPlace(this, data);
myLocation.setText(place.getName() + ", " + place.getAddress());
break;
}
}
}
// Ahh
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
private AdapterView.OnItemClickListener mAutocompleteClickListener
= new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final PlacesAutoCompleteAdapter.PlaceAutocomplete item = mPlacesAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
= new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
Log.e("place", "Place query did not complete. Error: " +
places.getStatus().toString());
return;
}
// Selecting the first object buffer.
final Place place = places.get(0);
}
};
}
public class PlacesAutoCompleteAdapter extends ArrayAdapter<PlacesAutoCompleteAdapter.PlaceAutocomplete> implements Filterable {
private static final String TAG = "PlaceAutocomplete";
/**
* Current results returned by this adapter.
*/
private ArrayList<PlaceAutocomplete> mResultList;
/**
* Handles autocomplete requests.
*/
private GoogleApiClient mGoogleApiClient;
/**
* The bounds used for Places Geo Data autocomplete API requests.
*/
private LatLngBounds mBounds;
/**
* The autocomplete filter used to restrict queries to a specific set of place types.
*/
private AutocompleteFilter mPlaceFilter;
/**
* Initializes with a resource for text rows and autocomplete query bounds.
*
* @see ArrayAdapter#ArrayAdapter(Context, int)
*/
public PlacesAutoCompleteAdapter(Context context, int resource, GoogleApiClient googleApiClient,
LatLngBounds bounds, AutocompleteFilter filter) {
super(context, resource);
mGoogleApiClient = googleApiClient;
mBounds = bounds;
mPlaceFilter = filter;
}
/**
* Sets the bounds for all subsequent queries.
*/
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
/**
* Returns the number of results received in the last autocomplete query.
*/
@Override
public int getCount() {
return mResultList.size();
}
/**
* Returns an item from the last autocomplete query.
*/
@Override
public PlaceAutocomplete getItem(int position) {
return mResultList.get(position);
}
/**
* Returns the filter for the current set of autocomplete results.
*/
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
mResultList = getAutocomplete(constraint);
if (mResultList != null) {
// The API successfully returned results.
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> getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i(TAG, "Starting autocomplete query for: " + constraint);
// Submit the query to the autocomplete API and retrieve a PendingResult that will
// contain the results when the query completes.
PendingResult<AutocompletePredictionBuffer> results =
Places.GeoDataApi
.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
mBounds, mPlaceFilter);
// This method should have been called off the main UI thread. Block and wait for at most 60s
// for a result from the API.
AutocompletePredictionBuffer autocompletePredictions = results
.await(60, TimeUnit.SECONDS);
// Confirm that the query completed successfully, otherwise return null
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
// Copy the results into our own data structure, because we can't hold onto the buffer.
// AutocompletePrediction objects encapsulate the API response (place ID and description).
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
// Get the details of this prediction and copy it into a new PlaceAutocomplete object.
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
prediction.getFullText(null)));
}
// Release the buffer now that all data has been copied.
autocompletePredictions.release();
return resultList;
}
Log.e(TAG, "Google API client is not connected for autocomplete query.");
return null;
}
/**
* Holder for Places Geo Data Autocomplete API results.
*/
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();
}
}
}
public类MainActivity扩展了AppCompatActivity{
私募股权投资公司Picker.IntentBuilder builder;
私募基金须完成转售申请;
专用按钮选择器;
私有自动完成文本视图myLocation;
私有静态最终整数位置\u选择器\u标志=1;
私有静态最终LatLngBounds边界\u更大\u SYDNEY=新LatLngBounds(
新车床(-34.041458150.790100),新车床(-33.682247151.383362);
受保护的GoogleapClient MGoogleapClient;
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mgoogleapclient=新的Googleapclient.Builder(此)
.addApi(Places.GEO_数据_API)
.build();
setContentView(R.layout.activity_main);
builder=newplacepicker.IntentBuilder();
myLocation=(AutoCompleteTextView)findViewById(R.id.myLocation);
mPlacesAdapter=newplacesautoCompleteAdapter(这个,android.R.layout.simple\u list\u item\u 1,
mGoogleApiClient,边界(大悉尼,空);
myLocation.setOnItemClickListener(mAutocompleteClickListener);
设置适配器(mPlacesAdapter);
pickerBtn=(按钮)findviewbyd(R.id.pickerBtn);
pickerBtn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
试一试{
builder=newplacepicker.IntentBuilder();
Intent=builder.build(MainActivity.this);
//通过请求由请求代码标识的结果来启动意图。
startActivityForResult(意图、地点、选择器、标志);
}捕获(谷歌游戏服务可修复例外){
谷歌PlayServiceSutil
.getErrorDialog(例如getConnectionStatusCode(),MainActivity.this,0);
}捕获(谷歌PlayServicesNotAvailableException){
Toast.makeText(MainActivity.this,“Google Play服务不可用。”,
吐司长度(长)
.show();
}
}
});
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(resultCode==RESULT\u OK){
开关(请求代码){
箱子位置\u选择器\u标志:
Place-Place=PlacePicker.getPlace(这个,数据);
myLocation.setText(place.getName()+“,“+place.getAddress());
打破
}
}
}
//啊
@凌驾
受保护的void onStart(){
super.onStart();
mGoogleApiClient.connect();
}
@凌驾
受保护的void onStop(){
mGoogleApiClient.disconnect();
super.onStop();
}
private AdapterView.OnItemClickListener Mauto完成ClickListener
=新AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
最终位置SautoCompleteAdapter.PlaceAutocomplete item=mPlacesAdapter.getItem(位置);
最终字符串placeId=String.valueOf(item.placeId);
Pendingreult placeResult=Places.GeoDataApi
.getPlaceById(mGoogleApiClient,placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
私有结果回调mUpdatePlaceDetailsCallback
=新结果回调(){
@凌驾
公共void onResult(PlaceBuffer places){
如果(!places.getStatus().issucess()){
Log.e(“地点”,“地点查询未完成。错误:”+
places.getStatus().toString());
返回;
}
//选择第一个对象缓冲区。
最终地点=地点。获取(0);
}
};
}
PlacesAutoCompleteAdapter.java
public class MainActivity extends AppCompatActivity {
private PlacePicker.IntentBuilder builder;
private PlacesAutoCompleteAdapter mPlacesAdapter;
private Button pickerBtn;
private AutoCompleteTextView myLocation;
private static final int PLACE_PICKER_FLAG = 1;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
protected GoogleApiClient mGoogleApiClient;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Places.GEO_DATA_API)
.build();
setContentView(R.layout.activity_main);
builder = new PlacePicker.IntentBuilder();
myLocation = (AutoCompleteTextView) findViewById(R.id.myLocation);
mPlacesAdapter = new PlacesAutoCompleteAdapter(this, android.R.layout.simple_list_item_1,
mGoogleApiClient, BOUNDS_GREATER_SYDNEY, null);
myLocation.setOnItemClickListener(mAutocompleteClickListener);
myLocation.setAdapter(mPlacesAdapter);
pickerBtn = (Button) findViewById(R.id.pickerBtn);
pickerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
builder = new PlacePicker.IntentBuilder();
Intent intent = builder.build(MainActivity.this);
// Start the Intent by requesting a result, identified by a request code.
startActivityForResult(intent, PLACE_PICKER_FLAG);
} catch (GooglePlayServicesRepairableException e) {
GooglePlayServicesUtil
.getErrorDialog(e.getConnectionStatusCode(), MainActivity.this, 0);
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(MainActivity.this, "Google Play Services is not available.",
Toast.LENGTH_LONG)
.show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PLACE_PICKER_FLAG:
Place place = PlacePicker.getPlace(this, data);
myLocation.setText(place.getName() + ", " + place.getAddress());
break;
}
}
}
// Ahh
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
private AdapterView.OnItemClickListener mAutocompleteClickListener
= new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final PlacesAutoCompleteAdapter.PlaceAutocomplete item = mPlacesAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
= new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
Log.e("place", "Place query did not complete. Error: " +
places.getStatus().toString());
return;
}
// Selecting the first object buffer.
final Place place = places.get(0);
}
};
}
public class PlacesAutoCompleteAdapter extends ArrayAdapter<PlacesAutoCompleteAdapter.PlaceAutocomplete> implements Filterable {
private static final String TAG = "PlaceAutocomplete";
/**
* Current results returned by this adapter.
*/
private ArrayList<PlaceAutocomplete> mResultList;
/**
* Handles autocomplete requests.
*/
private GoogleApiClient mGoogleApiClient;
/**
* The bounds used for Places Geo Data autocomplete API requests.
*/
private LatLngBounds mBounds;
/**
* The autocomplete filter used to restrict queries to a specific set of place types.
*/
private AutocompleteFilter mPlaceFilter;
/**
* Initializes with a resource for text rows and autocomplete query bounds.
*
* @see ArrayAdapter#ArrayAdapter(Context, int)
*/
public PlacesAutoCompleteAdapter(Context context, int resource, GoogleApiClient googleApiClient,
LatLngBounds bounds, AutocompleteFilter filter) {
super(context, resource);
mGoogleApiClient = googleApiClient;
mBounds = bounds;
mPlaceFilter = filter;
}
/**
* Sets the bounds for all subsequent queries.
*/
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
/**
* Returns the number of results received in the last autocomplete query.
*/
@Override
public int getCount() {
return mResultList.size();
}
/**
* Returns an item from the last autocomplete query.
*/
@Override
public PlaceAutocomplete getItem(int position) {
return mResultList.get(position);
}
/**
* Returns the filter for the current set of autocomplete results.
*/
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
mResultList = getAutocomplete(constraint);
if (mResultList != null) {
// The API successfully returned results.
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> getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i(TAG, "Starting autocomplete query for: " + constraint);
// Submit the query to the autocomplete API and retrieve a PendingResult that will
// contain the results when the query completes.
PendingResult<AutocompletePredictionBuffer> results =
Places.GeoDataApi
.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
mBounds, mPlaceFilter);
// This method should have been called off the main UI thread. Block and wait for at most 60s
// for a result from the API.
AutocompletePredictionBuffer autocompletePredictions = results
.await(60, TimeUnit.SECONDS);
// Confirm that the query completed successfully, otherwise return null
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
// Copy the results into our own data structure, because we can't hold onto the buffer.
// AutocompletePrediction objects encapsulate the API response (place ID and description).
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
// Get the details of this prediction and copy it into a new PlaceAutocomplete object.
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
prediction.getFullText(null)));
}
// Release the buffer now that all data has been copied.
autocompletePredictions.release();
return resultList;
}
Log.e(TAG, "Google API client is not connected for autocomplete query.");
return null;
}
/**
* Holder for Places Geo Data Autocomplete API results.
*/
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();
}
}
}
公共类PlacesAutoCompleteAdapter扩展ArrayAdapter实现可过滤{
私有静态最终字符串TAG=“PlaceAutocomplete”;
/**
*此适配器返回的当前结果。
*/
私有ArrayList mResultList;
/**
*处理自动完成请求。
*/
私人GoogleapClient MGoogleapClient;
/**
*用于放置地理数据自动完成API请求的边界。
*/
私人LatLngBounds mBounds;
/**
*自动完成筛选器用于将查询限制为一组特定的位置类型。
*/
专用自动完成过滤器;
/**
*使用文本行和自动完成查询边界的资源初始化。
*
*@see ArrayAdapter#ArrayAdapter(上下文,int)
*/
public PlacesAutoCompleteAdapter(上下文上下文、int资源、GoogleAppClient、GoogleAppClient、,
LatLngBounds边界,自动完成过滤器(过滤器){
超级(上下文、资源);
mGoogleApiClient=googleApiClient;
mBounds=边界;
mPlaceFilter=过滤器;
}
/**
*设置所有后续查询的边界。
*/
公共无效收进边界(LatLngBounds边界){
mBounds=边界;
}
/**
*返回上次自动完成查询中收到的结果数。
*/
@凌驾
public int getCount(){
返回mResultList.size();
}
/**
*返回上次自动完成查询中的项。
*/
@凌驾
公共场所自动完成getItem(内部位置){
返回mResultList.get(位置);
}
/**
*返回当前自动完成结果集的筛选器。
*/
@凌驾
公共过滤器getFilter(){
过滤器过滤器=新过滤器(){
@凌驾
受保护的筛选器结果性能筛选(CharSequence约束){
FilterResults results=新的FilterResults();
//如果未给出任何约束,则跳过自动完成查询。
if(约束!=null)