如何使用Google Places API搜索地址/地点? Android的

时间:2016-07-17 06:04:48

标签: android google-maps android-studio google-places

我想知道如何使用字符串来获取使用Google Places API的地址或地点的搜索结果。目前,我正在使用Geocoder获取搜索结果,但我得到的结果并不完整或与我当前的位置相关。请稍微描述一下,因为我之前没有使用过Google Places API。我看过this tutorial 但我无法安静地理解它。我将在EditText视图中输入用户的字符串输入,我想使用该字符串显示与我当前位置相关的匹配地址列表。

1 个答案:

答案 0 :(得分:0)

您好我在这里为您提供有关自动填充功能的简单示例,如果您希望您可以通过引用google api网站尝试其他功能。只需按照几个步骤。希望这有助于您理解并轻松完成工作

第1步。 在您的Activity中,您需要使用编辑文本作为文本更改的侦听器,然后调用places api

    et_Search.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

                placesTask = new PlacesTask();
                String[] toPass = new String[2];
                toPass[0] = s.toString();
                placesTask.execute(toPass);

        }
    });

第2步。  这里是要求google places api

    // Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String> {

    private String val = "";
    @Override
    protected String doInBackground(String... place) {
        // For storing data from web service
        String data = "";

        // Obtain browser key from https://code.google.com/apis/console
        String key = "key="+getResources().getString(R.string.google_server_key);

        String input="";

        try {
            input = "input=" + URLEncoder.encode(place[0], "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        String parameters = input+"&"+key + "&components=country:in";
        // Output format +gpsTracker.getLatitude() + "," + gpsTracker.getLongitude() + "&radius=20000
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;

        try{
            // Fetching the data from we service
            data = Webservices.ApiCallGet(url);
        }catch(Exception e){
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // Creating ParserTask
        parserTask = new ParserTask();

        String[] strData = new String[2];
        strData[0] = result;
        // Starting Parsing the JSON string returned by Web Service
        parserTask.execute(strData);
    }
}

第3步。获得结果

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

    JSONObject jObject;

    @Override
    protected List<HashMap<String, String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;

        PlaceJSONParser placeJsonParser = new PlaceJSONParser();


        try{
            jObject = new JSONObject(jsonData[0]);

            // Getting the parsed data as a List construct
            places = placeJsonParser.parse(jObject);

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }
        return places;
    }

    @Override
    protected void onPostExecute(List<HashMap<String, String>> result) {

        String[] from = new String[] { "description"};
        int[] to = new int[] { android.R.id.text1 };
            AutoCompleteAdapter adapter = new AutoCompleteAdapter(getBaseContext(), result);

            // Setting the adapter
            if(adapter != null && result != null )
                lv_SearchList.setAdapter(adapter);

    }
}

// Fetches  latitude & longitude from place id
private class LatLongTask extends AsyncTask<Void, Void, String> {

    private HashMap<String, String> placeMap;
    private ProgressDialog dialog;

    public LatLongTask(HashMap<String, String> placeMap){
        this.placeMap = placeMap;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(SearchActivity.this, "", "Please Wait...",
                true, false);
    }

    @Override
    protected String doInBackground(Void... place) {
        // For storing data from web service
        String data = "";

        // Obtain browser key from https://code.google.com/apis/console
        String key = "key="+getResources().getString(R.string.google_server_key);

        String input="";

        try {
            input = "placeid=" + URLEncoder.encode(placeMap.get("place_id"), "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // Building the parameters to the web service
        String parameters = input+"&"+key ;

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;

        try{
            // Fetching the data from we service
            data = Webservices.ApiCallGet(url);
        }catch(Exception e){
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if(dialog!= null && dialog.isShowing()){
            dialog.dismiss();
        }

        try {
            JSONObject jResult = new JSONObject(result);
            if(jResult.getString("status").equals("OK")) {
                JSONObject jsonObject = jResult.getJSONObject("result");
                JSONObject jGeometry = jsonObject.getJSONObject("geometry");
                JSONObject jLocation = jGeometry.getJSONObject("location");
                placeMap.put("lat", ""+jLocation.getString("lat"));
                placeMap.put("lng", ""+jLocation.getString("lng"));
                ArrayList<HashMap<String, String>> mapArrayList = new ArrayList<HashMap<String, String>>();
                mapArrayList.add(placeMap);
                Intent intent = new Intent();
                intent.putExtra("result",  mapArrayList);
                if (getParent() == null) {
                    setResult(Activity.RESULT_OK, intent);
                } else {
                    getParent().setResult(Activity.RESULT_OK, intent);
                }
                finish();
            }else{
                Utils.toastmessage(SearchActivity.this, "Please try again later.");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}

步骤4.创建此类

public class PlaceJSONParser {

/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){

    JSONArray jPlaces = null;
    try {
        /** Retrieves all the elements in the 'places' array */
        jPlaces = jObject.getJSONArray("predictions");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    /** Invoking getPlaces with the array of json object
     * where each json object represent a place
     */
    return getPlaces(jPlaces);
}

private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
    int placesCount = jPlaces.length();
    List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
    HashMap<String, String> place = null;

    /** Taking each place, parses and adds to list object */
    for(int i=0; i<placesCount;i++){
        try {
            /** Call getPlace with place JSON object to parse the place */
            place = getPlace((JSONObject)jPlaces.get(i));
            placesList.add(place);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return placesList;
}

/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){

    HashMap<String, String> place = new HashMap<String, String>();

    String id="";
    String reference="";
    String description="";
    String place_id = "";

    try {

        description = jPlace.getString("description");
        id = jPlace.getString("id");
        reference = jPlace.getString("reference");
        place_id = jPlace.getString("place_id");

        place.put("description", description);
        place.put("_id",id);
        place.put("reference",reference);
        place.put("place_id", place_id);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return place;
}
}