Google Place Autocomplete API调用入门

希瓦尼帕特尔

我正在使用Google place自动完成API调用。我从Google开发人员那边查找了参考。从那里我已经完成了一些代码,但是我没有得到结果,所以请帮助我找出我的错误……在此先感谢。

这是我的清单。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.googleautocompleteapi"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.googleautocompleteapi.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是我的java文件

public class MainActivity extends Activity implements OnItemClickListener{

    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 = "AIzaSyD1kYc0zUlKO6i4KfV-ecefi2II6cs4eFM";

    static final HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
    static final JsonFactory JSON_FACTORY = new JacksonFactory();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autocomplete);

        autoCompView.setText("Fisherman's Wharf, San Francisco, CA, United States");
        autoCompView.setAdapter(new PlacesAutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line));
        autoCompView.setOnItemClickListener(this);

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    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("?sensor=false&key=" + API_KEY);
            sb.append("&components=country:uk");
            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<String>(predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {
                resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }

        return resultList;
    }

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

    }


}
希瓦尼帕特尔

我正在回答我自己的问题...解决了..见下文

public class MainActivity extends Activity  implements OnItemClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AutoCompleteTextView places = (AutoCompleteTextView) findViewById(R.id.autocomplete);
        places.setAdapter(new PlacesAutoCompleteAdapter(this,android.R.layout.simple_dropdown_item_1line ));
        places.setOnItemClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        // TODO Auto-generated method stub
        String str = (String) adapterView.getItemAtPosition(position);
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

}

转接器类别

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

    private static final String LOG_TAG = "Places_api";

    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 = "-----";
    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=false&key=" + API_KEY);
            sb.append("&components=country:IN");
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));

            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            Log.d("====", "Requesst send");
            // 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
            Log.d("JSON","Parsing resultant JSON :)");
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

            // Extract the Place descriptions from the results
            resultList = new ArrayList<String>(predsJsonArray.length());
            Log.d("JSON","predsJsonArray has length " + predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {

                resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
                Log.d("JSON",resultList.get(i));
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }

        return 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() {
            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();
                }
            }

            public boolean onLoadClass(Class arg0) {
                // TODO Auto-generated method stub
                return false;
            }};
        return filter;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Google Place Autocomplete API下拉列表未显示在Modal中

来自分类Dev

使用Objective-C将Google Autocomplete Place Search API限制为特定国家/地区

来自分类Dev

Android:提供“此IP,网站或移动应用程序无权使用此API密钥的Google Place Autocomplete API”

来自分类Dev

为什么在 Google API 中尝试使用 iOS 版 Place Autocomplete 时只得到 5 个结果而不是更多?

来自分类Dev

Google places autocomplete api limits

来自分类Dev

解析Google Place API JSON

来自分类Dev

google place api图标列表

来自分类Dev

如何在MapKit JS中创建类似于Google的Place Autocomplete的自动完成查找

来自分类Dev

Google Place API(地方搜索器)

来自分类Dev

使用Google Place API获取事件

来自分类Dev

Google Place API在Android中显示错误

来自分类Dev

如何获得评论数Google Place API?

来自分类Dev

google place搜寻api和“ Listing by”文字

来自分类Dev

google-place-api返回null json

来自分类Dev

google place搜寻api和“ Listing by”文字

来自分类Dev

Google Place API限制-非使用限制

来自分类Dev

Google Map API-Infowindow显示Google Place API信息

来自分类Dev

Google Map API-Infowindow显示Google Place API信息

来自分类Dev

Google Place API:无法从 google place api android 获取大陆名称

来自分类Dev

在Android上的Google LatLngBounds中搜索Google Place API

来自分类Dev

Google Maps API Autocomplete - 如何仅输出街道名称?

来自分类Dev

如何请求Google Place API返回地点的ID?

来自分类Dev

显示来自Google API Place Photo响应的图像

来自分类Dev

Google Maps API place_changed事件未触发

来自分类Dev

Google Place Api无法通过凌空返回任何东西

来自分类Dev

在IOS中从Google Map Place API提取要求信息

来自分类Dev

Google Places API Place.TYPE_ADDRESS丢失?

来自分类Dev

AngularJS-Google Place自动完成API密钥

来自分类Dev

在Google Place API中显示超过50公里的地方

Related 相关文章

  1. 1

    Google Place Autocomplete API下拉列表未显示在Modal中

  2. 2

    使用Objective-C将Google Autocomplete Place Search API限制为特定国家/地区

  3. 3

    Android:提供“此IP,网站或移动应用程序无权使用此API密钥的Google Place Autocomplete API”

  4. 4

    为什么在 Google API 中尝试使用 iOS 版 Place Autocomplete 时只得到 5 个结果而不是更多?

  5. 5

    Google places autocomplete api limits

  6. 6

    解析Google Place API JSON

  7. 7

    google place api图标列表

  8. 8

    如何在MapKit JS中创建类似于Google的Place Autocomplete的自动完成查找

  9. 9

    Google Place API(地方搜索器)

  10. 10

    使用Google Place API获取事件

  11. 11

    Google Place API在Android中显示错误

  12. 12

    如何获得评论数Google Place API?

  13. 13

    google place搜寻api和“ Listing by”文字

  14. 14

    google-place-api返回null json

  15. 15

    google place搜寻api和“ Listing by”文字

  16. 16

    Google Place API限制-非使用限制

  17. 17

    Google Map API-Infowindow显示Google Place API信息

  18. 18

    Google Map API-Infowindow显示Google Place API信息

  19. 19

    Google Place API:无法从 google place api android 获取大陆名称

  20. 20

    在Android上的Google LatLngBounds中搜索Google Place API

  21. 21

    Google Maps API Autocomplete - 如何仅输出街道名称?

  22. 22

    如何请求Google Place API返回地点的ID?

  23. 23

    显示来自Google API Place Photo响应的图像

  24. 24

    Google Maps API place_changed事件未触发

  25. 25

    Google Place Api无法通过凌空返回任何东西

  26. 26

    在IOS中从Google Map Place API提取要求信息

  27. 27

    Google Places API Place.TYPE_ADDRESS丢失?

  28. 28

    AngularJS-Google Place自动完成API密钥

  29. 29

    在Google Place API中显示超过50公里的地方

热门标签

归档