2014-12-09 2 views
0

이것은 조금 이상합니다. Google places API를 따라 내 안드로이드 앱에 자동 완성 기능을 추가했습니다. 올바른 API 키가 있어도 Android 자동 완성에 대한 Google Places API 요청이 거부되었습니다. 나는 JSON 클라이언트로 확인하려고 시도하고 GET/POST를 요청했지만 여전히 내 코드가 Google API 자동 완성을 따르는 지 확인했기 때문에 동일한 오류가 발생했습니다. 오류를 해결하는 솔루션을 찾지 못했습니다. 일부 답변은 place_id로 센서를 제거하는 것이 좋습니다. 나는 모른다. 친절하게도 자동 완성 기능을 사용하는 데 도움이되는 해결책이나 제안을 잘 설명하십시오. 장소 Google Api - 자동 완성

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

enter image description here

+0

내가 내가 여기에 답을 찾은 것 같아 [링크] http://www.acnenomor.com/4055758p1/google-places-api-request-denied-for-android-autocomplete- 오른쪽 상단 API 키 –

+0

내 질문에 답하십시오. Google places API에 대한 서버 키 사용 http://stackoverflow.com/a/35476715/5439549 – Sadashiv

답변

0

안녕 동생 API 키와 함께이 URL을 시도 같이 사용 & 입력 = KIR

그 작업 형제 엉 = https://maps.googleapis.com/maps/api/place/autocomplete/json?sensor=true&key= API 키 & 언어를.

+0

멋진 Android 앱 또는 브라우저 애플리케이션 용 키를 사용해야합니까? –

+0

android application 그리고 브라우저에서도 사용할 수 있습니다. 반환 코드 json –

0

안드로이드 앱에서만 작동합니다. REST 클라이언트에서 시도하지 마십시오. 대신 앱을 디버깅하여 응답을 확인하십시오.

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

    } 
}; 

    } 

의 작업 ...이 생성 서버 키처럼 수행하고 안드로이드 사용 autoacmpltere에서 구글 API를 콘솔에서 서버 키를 생성하는 모든 수 있도록 허용 모두 다음에서 구글 feture 가능 권한 그것의 일하는 형제는 이것을 시도하십시오 ....

+0

Mapdatalist를 유형으로 확인할 수 없으므로 Mapdatalist 클래스를 만들지 않으므로이 코드를 ArrayList 으로 변경하겠습니다. 맞나요? –

+0

버디 내가 해결할 수 없다

+0

u는 간단한 문자열을 사용할 수있다. – wadali

0

그래서 jaswinder는 내가 가정 할 때 place_id로 센서를 바꾸는 것이 필요하고 내 try catch도 코드 조각처럼 보이게해야합니다.

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; 

당신이 설명한대로 서버 키를 만들 수 있습니다. 그러면 그때 가야합니다. 감사합니다

0
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. 

희망이 코드는 도움이 되십시오. 브라우저 응용 프로그램 용 키를 사용하고 콘솔의 Api 및 Goople 맵 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; 

} 

}

관련 문제