Google商家信息详情搜索System.err

时间:2015-04-30 12:29:47

标签: java android google-places-api

我正在尝试使用AutoCompleteTextView按名称找到一家餐馆,它成功获取了地点ID。我还在浏览器中手动检查了http请求,并以正确的信息响应。执行此代码时,Eclipse中的LogCat控制台中会显示system.err。我的代码如下;

public class AdvancedSearch extends Activity implements OnItemClickListener {

    private static final String LOG_TAG = "com.lw276.justdine";

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

    // ------------ make your specific key ------------
    private static final String API_KEY = "MyAPIKEY";

    private Activity context = this;
    static HashMap<String, String> place;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advanced_search);
        final AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
        autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this,
                R.layout.list_item));
        autoCompView.setOnItemClickListener(this);
        Button btnAdvancedSearch = (Button) findViewById(R.id.advanced_search_btn);
        btnAdvancedSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = autoCompView.getText().toString();
                if(place.containsKey(str)){
                    String placeId = place.get(str);
                    Log.d("advancedSearchBtn: placeId = ", placeId);
                    Log.i("advancedSearchBtn", "Search button has been pressed");
                    Intent i = new Intent(context, GoogleMap.class);
                    i.putExtra("advancedSearch", placeId);
                    startActivity(i);
                } else {
                    Toast.makeText(context, "Please select an item from the autocomplete list", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    public void onItemClick(AdapterView<?> adapterView, View view,
            int position, long id) {
//      String str = (String) adapterView.getItemAtPosition(position);
//      Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    public static 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());
            System.out.println("URL: " + url);
            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");
            resultList = new ArrayList<String>(predsJsonArray.length());
            place = new HashMap<String, String>();
            for (int i = 0; i < predsJsonArray.length(); i++) {
                    System.out.println(predsJsonArray.getJSONObject(i).getString(
                            "description"));
                    System.out
                            .println("============================================================");
                    resultList.add(predsJsonArray.getJSONObject(i).getString(
                            "description"));

                 String description = predsJsonArray.getJSONObject(i).getString("description");
                 String placeId = predsJsonArray.getJSONObject(i).getString("place_id");
                 place.put( description, placeId);
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }
        return resultList;
    }

    class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String>
            implements Filterable {
        private ArrayList<String> resultList;

        public GooglePlacesAutocompleteAdapter(Context context,
                int textViewResourceId) {
            super(context, textViewResourceId);
        }

        @Override
        public int getCount() {
            return resultList.size();
        }

//      @Override
//      public HashMap<String, String> getItem(int index) {
//         return resultList.get(index);
//      }

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

}

googlePlaces示例=

https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJCSWGvY-FdUgRpGdg10FTIIg&key="MY_API_KEY"

为什么没有人在我的地图片段上放置任何标记,这是显而易见的吗?

LogCat的错误: http://pastebin.com/T1AFbw3s

Google地图和标记类: http://pastebin.com/hT2XwuE2

2 个答案:

答案 0 :(得分:1)

  1. 您遇到的错误是由于在GoogleMap活动的第193行错误地解析了Json:

       JSONArray placesArray = resultObject.getJSONArray("results");
    
  2. 我认为密钥是result而不是results。 如果能看到json响应,我可以给你一个更好的解释。与此同时, 我还建议您使用Gson库来解析对象的json响应,而不是手动映射它们。这会更容易。

      需要手动添加
    1. Markers

      private void addMarker(String name, double lat, double long){
         LatLng latlong = LatLng.newInstance(lat, long);
         MarkerOptions markerOptions = MarkerOptions.newInstance();
         markerOptions.setIcon(Icon.newInstance("/img/icon.png"));
         markerOptions.setTitle(name);  
         Marker marker = new Marker(latlong, markerOptions);
         map.addOverlay(marker);
      }
      

答案 1 :(得分:0)

事实证明,因为我使用相同的代码在地图上添加标记,所以当使用详细搜索来识别单个地点时,JSONArray类型与结果集不兼容......如果这有意义。 我不得不通过检查附近的搜索是否正在执行或详细搜索来将两者分开。以下是仅供详细信息搜索的代码:

resultObject = resultObject.getJSONObject("result"); // <---
                    places = new MarkerOptions[1];
                    LatLng placeLL = null;
                    String placeName = "";
                    String vicinity = "";
                    try {
                        JSONObject placeObject = resultObject;
                        JSONObject loc = placeObject.getJSONObject(
                                "geometry").getJSONObject("location");
                        placeLL = new LatLng(Double.valueOf(loc
                                .getString("lat")), Double.valueOf(loc
                                .getString("lng")));
                        vicinity = placeObject.getString("vicinity");
                        placeName = placeObject.getString("name");
                    } catch (JSONException jse) {
                        missingValue = true;
                        jse.printStackTrace();
                    }
                    if (missingValue){
                        result = null;
                    } else {
                        places[0] = new MarkerOptions().position(placeLL)
                                .title(placeName).snippet(vicinity);
                    }