谷歌地点详细信息搜索系统。System.err。

3

我正在尝试使用AutoCompleteTextView通过名称查找餐厅,它成功获取了地点ID。我还手动在浏览器中检查了http请求,并得到了正确的信息响应。但是执行以下代码时,Eclipse中的LogCat控制台显示了一个系统错误:

```java //代码示例 ```

我的代码如下:

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 Maps和Markers类: http://pastebin.com/hT2XwuE2

2个回答

1
  1. The error you are having is due to parsing the Json incorrectly at line 193 of GoogleMap activity:

       JSONArray placesArray = resultObject.getJSONArray("results");
    
我认为关键是 result 而不是 results。 如果我能看到 JSON 响应,我可以给你更好的解释。同时, 我建议您使用 Gson 库将 JSON 响应解析为对象,而不是手动映射它们。这样会更容易一些。
  1. Markers need to be added manually:

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

我已经添加了System.err日志,并将处理地图和标记的Java类链接到PasteBin。 - Luke Willmer
我已经对GoogleMap活动进行了更改,但无论是详细搜索还是附近搜索都没有给我任何结果。 编辑: 然而,我已经仔细检查了日志,你是正确的,似乎缺少结果集。 - Luke Willmer

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接