How can we restrict google map autocomplete to only a particular city?

前端 未结 4 1599
逝去的感伤
逝去的感伤 2020-12-11 13:45

My requirement is to get google places autocomplete suggestion only for the places in Bangalore, but if I search for any other place apart from bangalore then also I get the

相关标签:
4条回答
  • 2020-12-11 14:00

    Google is not providing autocomplete for particular city but we can do it manually. in my case i want to display address of 'Maharashtra' state.

      this.GoogleAutocomplete = new google.maps.places.AutocompleteService();
    
        this.GoogleAutocomplete.getPlacePredictions(
      {
        input: this.autocompleteFrom.input,
        types: ['geocode'],
        componentRestrictions: { country: 'in' },
      },
      (predictions, status) => {
        this.autocompleteItemsFrom = [];
        this.zone.run(() => {
          if (predictions) {
            console.log(predictions)
            predictions.forEach((prediction) => {
              var statearray = prediction.description.split(",")
              var state = statearray[statearray.length - 2]
              if(state === ' Maharashtra'){
                this.autocompleteItemsFrom.push(prediction);
              }
            });
          }
        });
      });
    

    i hope it will help you.

    0 讨论(0)
  • 2020-12-11 14:02

    Try like this.

    var bangaloreBounds = new google.maps.LatLngBounds(
       new google.maps.LatLng(12.864162, 77.438610),
       new google.maps.LatLng(13.139807, 77.711895));
    
    var autocomplete = new google.maps.places.Autocomplete(this, {
       bounds: bangaloreBounds,
       strictBounds: true,
    });
    
    autocomplete.addListener('place_changed', function () {
    
    });
    

    Note: The URL should be: https://maps.googleapis.com/maps/api/js?libraries=places&key=YOUR_API_KEY

    strictBounds option was added in version 3.27 of Maps JavaScript API which is currently (January 2017) the experimental version.

    0 讨论(0)
  • 2020-12-11 14:07

    I think that you can try this:

    var cityBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(25.341233, 68.289986),
      new google.maps.LatLng(25.450715, 68.428345));
    
    var options = {
      bounds: cityBounds,
      types: ['geocode'],
      componentRestrictions: {country: 'est'}
    };
    

    Replace LatLng value with your values and country with your country code.

    0 讨论(0)
  • 2020-12-11 14:15

    You can use bounds to bias results, but there is no strict filter by city in places autocomplete at the moment.

    You can find a feature request to add more strict filters in the public issue tracker:

    https://code.google.com/p/gmaps-api-issues/issues/detail?id=4433

    Please star this feature request to express your interest and receive updates from Google.

    0 讨论(0)
提交回复
热议问题