Is there a way to restrict the Google Places Autocomplete to search a city's streets?

前端 未结 4 725
天命终不由人
天命终不由人 2021-02-05 21:10

Can I restrict the search to a city\'s streets when using the Google Places Autocomplete?

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 21:56

    You can set the Autocomplete options to use geocode as the type, which will restrict the results that are returned to addresses:

    var input = document.getElementById( 'searchTextField' );
    var options = {
      bounds: yourBounds,
      types: ['geocode']
    };
    
    autocomplete = new google.maps.places.Autocomplete( input, options );
    

    There is no way to restrict the results to just streets, but this will largely achieve what you want. If you set yourBounds correctly, maybe limited to the area of a city, it will get you as close as currently possible.

    Update responding to the comment:

    If you want to start by entering a city, you can bind the map's bounds to the Autocompletes bounds, which will have the map set its viewport automatically when a city is selected in the Autocomplete:

    var options = {
      bounds: yourBounds,
      types: ['(cities)']
    };
    autocomplete =
        new google.maps.places.Autocomplete( input, options );
    // This will bind the map's bounds to the Autocomplete's bounds:
    autocomplete.bindTo('bounds', map);
    

    Then, you can update the Autocomplete's types, similar to the above, to have it return addresses:

    autocomplete.setTypes( [ "geocode" ] );
    

    From there, you can have a read of the Places Library API Docs.

提交回复
热议问题