0

Is it possible to restrict autocomplete places to return result only within 2km region from my current place? and within city?

I'm using code from official website I tried using set origin to my current location and bounds but I'm not getting desired result, by trying this I'm getting result from within country not from city and not from 2km from my current location, how can I achieve this?

Thanks In Advance

blackHawk
  • 6,047
  • 13
  • 57
  • 100

1 Answers1

0

There will not be a direct method to specify the current location and radius, But you can achieve the same after simple data processing.

public void openPlacePickerActivity() {
    List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG);

    //Specify your radius
    double radius = 2.0;

    // Get Rectangular Bounds from your current location
    double[] boundsFromLatLng = getBoundsFromLatLng(radius, -33.880490f, 151.184363f);
    
    Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
            // Specify Rectangular Bounds to restrict the API result.
            // Ref: https://developers.google.com/places/android-sdk/autocomplete#restrict_results_to_a_specific_region
            .setLocationRestriction(RectangularBounds.newInstance(
                    new LatLng(boundsFromLatLng[0], boundsFromLatLng[1]),
                    new LatLng(boundsFromLatLng[2], boundsFromLatLng[3])
            ))
            .build(mActivity);

    startActivityForResult(intent, 101);
}

/**
 * Please check below link for an understanding of the method
 * Ref: https://stackoverflow.com/questions/238260/how-to-calculate-the-bounding-box-for-a-given-lat-lng-location#41298946
 */
public double[] getBoundsFromLatLng(double radius, double lat, double lng) {
    double lat_change = radius / 111.2f;
    double lon_change = Math.abs(Math.cos(lat * (Math.PI / 180)));
    return new double[]{
            lat - lat_change,
            lng - lon_change,
            lat + lat_change,
            lng + lon_change
    };
}
Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
  • Im not using place picker, its just getting result of autocomplete places api, not using place picker – blackHawk Aug 12 '20 at 14:45
  • Then it will be very easy. Ref: https://developers.google.com/places/web-service/autocomplete Example Link: https://maps.googleapis.com/maps/api/place/autocomplete/xml?location=37.76999,-122.44696&radius=2000&strictbounds&key=YOUR_API_KEY – Dhaval Patel Aug 12 '20 at 14:46
  • Its of web not android @Dhaval Patel – blackHawk Aug 12 '20 at 14:52