【问题标题】:Places Google Api - Autocomplete地点 Google Api - 自动完成
【发布时间】:2015-02-07 00:36:15
【问题描述】:

这有点奇怪,我按照 Google Places API 为我的 android 应用程序添加了自动完成功能。即使使用正确的 api 密钥,Android 自动完成的 Google Places API 请求也会被拒绝。我什至尝试检查 JSON 客户端并请求 GET/POST 仍然相同的错误,因为我确定我的代码相应地遵循了 google api 自动完成的集成。我还没有找到任何解决该错误的解决方案。一些答案建议使用 place_id 移除传感器。我不知道。请解释 可以帮助我使自动完成功能正常工作的解决方案或建议。

https://maps.googleapis.com/maps/api/place/autocomplete/json/?sensor=false&key=API_KEY&components=country=us&input=california

【问题讨论】:

标签: android json api google-maps autocomplete


【解决方案1】:

你好兄弟,用你的 api 密钥试试这个 url: https://maps.googleapis.com/maps/api/place/autocomplete/json?sensor=true&key=api key&language=en&input=kir

它的工作兄弟。

【讨论】:

  • 很酷,所以我必须将密钥用于 android 应用程序或浏览器应用程序吗?
  • android 应用程序,您也可以在浏览器中使用它返回 json
【解决方案2】:

它只适用于安卓应用。不要在 REST 客户端中尝试。而是尝试调试您的应用以查看响应。

【讨论】:

    【解决方案3】:

    所以 jaswinder 我需要做的更改是我假设的将传感器替换为 place_id 并且我的 try catch 也应该更改为看起来像您的代码 sn-p;

    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(TAG, "Cannot process JSON results", e);
    
        }
    
        return resultList;
    

    然后我可以按照您的说明创建服务器密钥,那我应该很好。谢谢

    【讨论】:

      【解决方案4】:
      public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements
          Filterable {
      private ArrayList<MapdataList> resultList;
      
      public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
          super(context, textViewResourceId);
      
      }
      
      @Override
      public int getCount() {
          return resultList.size();
      }
      
      @Override
      public String getItem(int index) {
      
          MapdataList data = resultList.get(index);
      
          return data.getPlaceName();
      
      }
      
      public String mthod(int index) {
          MapdataList data = resultList.get(index);
      
          return data.getPlaceID();
      
      }
      
      @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 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 = "serverkry";
      
      private ArrayList<MapdataList> autocomplete(String input) {
          ArrayList<MapdataList> 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("&components=country:uk");
              sb.append("&sensor=true");
              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<MapdataList>(predsJsonArray.length());
              for (int i = 0; i < predsJsonArray.length(); i++) {
      
                  MapdataList mapData = new MapdataList();
                  mapData.setPlaceName(predsJsonArray.getJSONObject(i).getString(
                          "description"));
                  mapData.setPlaceID(predsJsonArray.getJSONObject(i).getString(
                          "place_id"));
      
                  resultList.add(mapData);
      
                  // resultList.add(predsJsonArray.getJSONObject(i).getString(
                  // "description"));
                  // resultList.add(1,predsJsonArray.getJSONObject(i).getString(
                  // "place_id"));
              }
          } catch (JSONException e) {
              Log.e(LOG_TAG, "Cannot process JSON results", e);
          }
      
          return resultList;
        }
        }
      

      `

      public class TestMapAutocomplete extends Activity {
      PlacesAutoCompleteAdapter obj;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_test_map_autocomplete);
      
          AutoCompleteTextView YY = (AutoCompleteTextView) findViewById(R.id.Google_autoCompleteTextView1);
          obj = new PlacesAutoCompleteAdapter(this, R.layout.google_list_items);
          YY.setAdapter(obj);
      
          YY.setOnItemClickListener(getPlaceId);
      
      }
      
      public OnItemClickListener getPlaceId = new OnItemClickListener() {
      
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position,
                  long id) {
              // TODO Auto-generated method stub
      
              // int dd= (Integer) parent.getItemAtPosition(position);
              String mcityselect = obj.mthod(position);
              // String mcityselect = (String) parent.getItemAtPosition(position);
              String mcityccselect = (String) parent.getItemAtPosition(position);
      
          }
      };
      
        }
      

      它的工作......像这样创建服务器密钥并允许所有然后在android中使用autoacmpltere在google api控制台中创建一个服务器密钥并允许所有然后在权限中启用google feture 它的工作兄弟试试这个....

      【讨论】:

      • Mapdatalist 无法解析为类型,所以我不会创建 Mapdatalist 类,我只是将其更改为 ArrayList 是否正确?
      • 你可以使用简单的字符串
      • Mapdata 是我创建的接口,如果您想获取单个值,则可以在变量中获取两个以上的数组列表,因此您可以使用 ArrayList
      • 我使用了简单的字符串,但请查看我的地址建议的屏幕截图,那里有乱七八糟的随机内容。我如何删除这样的坏建议。
      【解决方案5】:
      Hey guys now the autocomplete is working Jaswinder I just added place_id where you commented it out and wala! it works like a charm.
      

      希望此代码对某人有所帮助。我使用 Key for browser application 并在控制台中启用了 Places api 和 Goople map api。

      private class PlacesAutoCompleteAdapter extends ArrayAdapter<String>
              implements Filterable {
          private ArrayList<String> resultList;
      
          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;
          }
      }
      
      // Get array list of addresses
      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("?sensor=true&key="
      
              + API_KEY);
      
              // for current country.Get the country code by SIM
      
              // If you run this in emulator then it will get country name is
              // "us".
      
              String cName = getCountryCode();
      
              if (cName != null) {
                  countryName = cName;
              } else {
                  countryName = "za";
              }
              sb.append("&components=country:" + countryName);
              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(TAG, "Error processing Places API URL", e);
      
              return resultList;
      
          } catch (IOException e) {
      
              Log.e(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"));
      
                  resultList.add(predsJsonArray.getJSONObject(i).getString(
                          "place_id"));
      
              }
      
          } catch (JSONException e) {
      
              Log.e(TAG, "Cannot process JSON results", e);
      
          }
      
          return resultList;
      
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-23
        • 2012-08-09
        • 1970-01-01
        • 2023-03-12
        • 2015-12-24
        • 2017-10-20
        • 2012-03-15
        相关资源
        最近更新 更多