这是我在谷歌地图上搜索地点的代码。该应用程序工作正常,但问题是我只能找到街道,但我找不到像肯德基,星巴克,沃尔玛这样的地方....请告诉我该怎么做。
public class MainActivity extends FragmentActivity implements OnClickListener,LocationListener {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
AutoCompleteTextView autoCompleteTextView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.et_location);
autoCompleteTextView.requestFocus();
autoCompleteTextView.setAdapter(new PlacesAutoCompleteAdapter(
MainActivity.this, R.layout.list_item_autocomplete));
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
// Getting reference to btn_find of the layout activity_main
Button btn_find = (Button) findViewById(R.id.btn_find);
Button searchplaces=(Button) findViewById(R.id.searchplaces);
Button howitwork=(Button) findViewById(R.id.howitwork);
// Defining button click event listener for the find button
OnClickListener findClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// Getting reference to EditText to get the user input location
// Getting user input location
String searchlocation = autoCompleteTextView.getText().toString();
if (searchlocation != null && !searchlocation.equals("")) {
new GeocoderTask().execute(searchlocation);
}
}
};
// Set button click event listener for the find button
btn_find.setOnClickListener(findClickListener);
// An AsyncTask class for accessing the GeoCoding Web Service
public class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
@Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
@Override
protected void onPostExecute(List<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
}
else{
// Adding Markers on MainActivity Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in MainActivity Map
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
latLng, 14));
}}
}
}
这是PlaceAdapter类
public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
private static final String LOG_TAG = "ExampleApp";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "AIzaSyA5ipjFYgrW85dNp4MuA-FYzI2de3frHfk";
public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public int getCount() {
return resultList.size();
}
@Override
public String getItem(int index) {
return resultList.get(index);
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}};
return filter;
}
private ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
}
答案 0 :(得分:0)
您尚未包含&#34;类型&#34;参数,用于定义要包含在自动填充搜索结果中的咖啡馆或餐馆。请查看此example,您将更好地了解如何在代码中实现它。所有String类型将由管道分隔,管道将是doInBackground()方法的一部分,该方法将负责通过来自Google服务器的http调用获取结果。我附上了一段代码,您可以参考链接中的示例。
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
// Separeate your place types by PIPE symbol "|"
// If you want all types places make it as null
// Check list of types supported by google
//
String types = "cafe|restaurant"; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 1000; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),
gps.getLongitude(), radius, types);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
希望这会有所帮助!!