Rohit Rasure
Rohit Rasure

Reputation: 11

Fetch auto completed address using google map API for particular city

I am building an android app where I am using google map API for fetching location. I had set Limit to country (India) addresses. Is there any way to set a limit for the state (Maharashtra) and city (Pune) wise in it?

Below is my code for fetching addresses using google map API key

List < Place.Field > placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG, Place.Field.TYPES);

FetchPlaceRequest request = null;
if (placeID != null) {
    request = FetchPlaceRequest.builder(placeID, placeFields)

        .build();
}

if (request != null) {
    placesClient.fetchPlace(request).addOnSuccessListener(new OnSuccessListener < FetchPlaceResponse > () {
        @SuppressLint("SetTextI18n")
        @Override
        public void onSuccess(FetchPlaceResponse task) {
            localityAddressEdt.setText(task.getPlace().getName() + "\n" + task.getPlace().getAddress());
            pinCode = "";
            latLng = task.getPlace().getLatLng();

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            e.printStackTrace();
        }
    });
}
} catch (Exception e) {
    e.printStackTrace();
}

Below is my adapter code (getAutocomplete method is used for country restriction):

public class AutoCompleteAdapter extends ArrayAdapter < AutocompletePrediction > implements Filterable {

    private ArrayList < AutocompletePrediction > mResultList;
    private PlacesClient placesClient;

    public AutoCompleteAdapter(Context context, PlacesClient placesClient) {
        super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
        this.placesClient = placesClient;
    }

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

    @Override
    public AutocompletePrediction getItem(int position) {
        return mResultList.get(position);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        View row = super.getView(position, convertView, parent);

        AutocompletePrediction item = getItem(position);

        TextView textView1 = row.findViewById(android.R.id.text1);
        TextView textView2 = row.findViewById(android.R.id.text2);
        if (item != null) {
            textView1.setText(item.getPrimaryText(null));
            textView2.setText(item.getSecondaryText(null));
        }

        return row;
    }

    @NonNull
    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {

                FilterResults results = new FilterResults();

                // We need a separate list to store the results, since
                // this is run asynchronously.
                ArrayList < AutocompletePrediction > filterData = new ArrayList < > ();

                // Skip the autocomplete query if no constraints are given.
                if (charSequence != null) {
                    // Query the autocomplete API for the (constraint) search string.
                    filterData = getAutocomplete(charSequence);
                }

                results.values = filterData;
                if (filterData != null) {
                    results.count = filterData.size();
                } else {
                    results.count = 0;
                }

                return results;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence charSequence, FilterResults results) {

                if (results != null && results.count > 0) {
                    // The API returned at least one result, update the data.
                    mResultList = (ArrayList < AutocompletePrediction > ) results.values;
                    notifyDataSetChanged();
                } else {
                    // The API did not return any results, invalidate the data set.
                    notifyDataSetInvalidated();
                }
            }

            @Override
            public CharSequence convertResultToString(Object resultValue) {
                // Override this method to display a readable result in the AutocompleteTextView
                // when clicked.
                if (resultValue instanceof AutocompletePrediction) {
                    return ((AutocompletePrediction) resultValue).getFullText(null);
                } else {
                    return super.convertResultToString(resultValue);
                }
            }
        };
    }

    private ArrayList < AutocompletePrediction > getAutocomplete(CharSequence constraint) {

        final FindAutocompletePredictionsRequest.Builder requestBuilder =
            FindAutocompletePredictionsRequest.builder()
            .setQuery(constraint.toString())
            .setCountry("IN")
            .setSessionToken(AutocompleteSessionToken.newInstance());


        Task < FindAutocompletePredictionsResponse > results =
            placesClient.findAutocompletePredictions(requestBuilder.build());


        //Wait to get results.
        try {
            Tasks.await(results, 60, TimeUnit.SECONDS);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            e.printStackTrace();
        }

        if (results.isSuccessful()) {
            if (results.getResult() != null) {
                return (ArrayList < AutocompletePrediction > ) results.getResult().getAutocompletePredictions();
            }
            return null;
        } else {
            return null;
        }
    }
}

Upvotes: 1

Views: 400

Answers (1)

Ashwini Saini
Ashwini Saini

Reputation: 1374

FindAutocompletePredictionsRequest.Builder have two public methods setLocationBias() and setLocationRestriction() that can help you fetch result of particulate city

setLocationBias() will provide you result that biased towards your specific location. Predictions will not necessarily be within the location specified. Still the outside result can appear but they will have lower priority.

setLocationRestriction() will impose complete restriction on result and only show result that are within the location specified.

You can use this in your code like

final FindAutocompletePredictionsRequest.Builder requestBuilder =
            FindAutocompletePredictionsRequest.builder()
                    .setQuery(constraint.toString())
                    .setCountry("IN")
                    .setLocationRestriction(getLocationRestriction())
                    .setSessionToken(AutocompleteSessionToken.newInstance());


    private LocationRestriction getLocationRestriction() {
        return getBounds();
      }


    private RectangularBounds getBounds() {

        // south-west coordinate of your specific region
        LatLng southWestLatLang = new LatLng(26.889599, 75.743508);

        // north- east coordinate of your specific region
        LatLng northEastLatLang = new LatLng(26.945622, 75.849623);

        LatLngBounds bounds = new LatLngBounds(southWestLatLang, northEastLatLang);


        return RectangularBounds.newInstance(bounds);
    }

if you want to learn more about LatLang Bound, you can see the documentation here

Extra:- here you can find a really good Git repo of Maps from Google, that include sample project of place autocomplete

Upvotes: 1

Related Questions