Google 地点详情搜索 System.err

Google Places Details search System.err

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

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 地图和标记 class: http://pastebin.com/hT2XwuE2

  1. 您遇到的错误是由于在 GoogleMap activity:

    的第 193 行错误地解析了 Json
       JSONArray placesArray = resultObject.getJSONArray("results");
    

我认为关键是 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);
    }
    

事实证明,因为我使用相同的代码将标记添加到地图上,所以当使用详细搜索来识别单个地点时,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);
                    }