在PlaceAutocomplete(Google Api)中预先填充地址

时间:2017-06-16 12:39:31

标签: android google-maps autocomplete google-api

我已经在我的android项目中实现了PlaceAutocomplete一切正常,但是根据它的工作时调用此(PlaceAutocomplete)活动显示为空

enter image description here

使用此代码启动代码:

Intent intent =new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).build(getActivity());
startActivityForResult(intent, 0);

但是根据我的项目要求,我需要预先填充先前选择的地址(例如,我在第一次选择了任何地址并将该地址设置到任何文本字段中,现在用户想要编辑该地址但是如果用户点击在文本视图上自动完成显示为空)。

我已经尝试了很多,但没有找到任何解决方案 它有什么办法在android ???

实现

3 个答案:

答案 0 :(得分:3)

找到它。

我之前期待这个答案。

  

PlaceAutocomplete.IntentBuilder类有方法,即   的 zzfd(@Nullable String var1)

它需要一个字符串值(如果你想预填充你的地址)。因此,您可以在调用startActivityForResult()时使用此功能。

代码就像:

Intent intent =new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                    .zzfd(your_text_View.getText().toString())
                                    .build(getActivity());
startActivityForResult(intent, 1);

如果您在启动时没有地址,则可以在zzfd()中传递null。

  

您也可以在“initial_query” KEY上发送地址,这也可以   相同。

例如:

Intent intent =new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                   .build(getActivity());
if (!TextUtils.isEmpty(your_text_View.getText().toString())) {
intent.putExtra("initial_query", (your_text_View.getText().toString());
} else {
   intent.removeExtra("initial_query");
}
startActivityForResult(intent, 1);

答案 1 :(得分:1)

为地点创建自定义自动完整文字视图:

XML:

<AutoCompleteTextView
                    android:id="@+id/location_Et"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_toStartOf="@+id/textCancel"
                    android:background="@drawable/search_box_bg"
                    android:drawablePadding="8dp"
                    android:drawableStart="@drawable/ic_search_grey_700_24dp"
                    android:ellipsize="end"
                    android:focusableInTouchMode="true"
                    android:hint="Search Location"
                    android:imeOptions="actionSearch"
                    android:inputType="textNoSuggestions"
                    android:lines="1"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp"
                    android:textColor="@color/standard_gray"
                    android:textCursorDrawable="@null"
                    android:textSize="18sp"
                    app:fontFileName="ProximaNova-Regular.otf"/>

活动:

locationEt = (AutoCompleteTextView) findViewById(R.id.location_Et);

        final PlacesAutoCompleteAdapter adapterPopUpDestination = new PlacesAutoCompleteAdapter(CustomLocationSelectionActivity.this, R.layout.autocomplete_list_text);
        locationEt.setAdapter(adapterPopUpDestination);

        locationEt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String address = adapterPopUpDestination.getItem(i);

            }
        });

适配器:

public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
    public static final String LOG_TAG = "ImpactForce";
    String textaddress;
    private ArrayList<String> resultList = new ArrayList<String>();
    private LayoutInflater inflater;
    private ViewHolder holder;

    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        if (resultList.size() > index) {
            return resultList.get(index);
        }
        return "";
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getMyView(position, convertView, parent);
    }

    private View getMyView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.autocomplete_list_text, parent, false);
            holder = new ViewHolder();

            holder.addressTitle = (TextView) convertView.findViewById(R.id.textViewTitleHeader);
            holder.address = (TextView) convertView.findViewById(R.id.textViewTitleSub);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        try {
            String address = getItem(position);

            String add[] = address.split(",");

            holder.addressTitle.setText(add[0]);
            holder.address.setText(address);
        } catch (Exception e) {
        }
        return convertView;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getMyView(position, convertView, parent);
    }

    @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.
                    if (Utility.isOnline(getContext())) {
                        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 ArrayList<String> autocomplete(String input) {

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        try {
            //https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Paris&types=geocode&key=YOUR_API_KEY
            StringBuilder sb = new StringBuilder(NetworkConstant.PLACES_API_BASE
                                                         + NetworkConstant.TYPE_AUTOCOMPLETE + NetworkConstant.OUT_JSON);
            //sb.append("&types=geocode&key=" + Constant.PLACES_AUTOCOMPLETE_API_KEY);
            sb.append("?sensor=false&key=" + NetworkConstant.PLACES_AUTOCOMPLETE_API_KEY);

            // sb.append("&location=" + BeanLocation.getLocation().getLatitude()
            // + "," + BeanLocation.getLocation().getLongitude());
            sb.append("&radius=500");
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));
            Log.w("url data", "" + sb.toString());
            // AppLog.Log("PlaceAdapter", "Place Url : " + sb.toString());
            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            Log.w("url data", "" + sb.toString());
            // 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
            // System.out.println(jsonResults.toString());
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

            // Extract the Place descriptions from the results
            resultList.clear();
            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 ViewHolder {

        TextView address;
        TextView addressTitle;
    }

答案 2 :(得分:0)

这对我有用。

implementation 'com.google.android.libraries.places:places:2.3.0'

意图

List<Place.Field> fields = Arrays.asList(
            Place.Field.ID,
            Place.Field.NAME,
            Place.Field.ADDRESS,
            Place.Field.LAT_LNG);
    // Start the autocomplete intent.
    Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields)
            .setInitialQuery(addressTexts)
            .build(getActivity());
    startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

现在它具有用于初始查询的.setInitialQuery(<your address texts>)方法。