hogard hogard - 17 days ago 7
Javascript Question

Google map Auto Complete filter by country using bounds

How to restrict the autocomplete suggestions only for US ( country). Here is my code so far,

<div class="search-result">
<form action="" method="post" class="clearfix">
<input type="text" placeholder="Enter City or Zip Code" class="searchBox" id="search-result" autocomplete="on">
<button type="submit" class="btn btn-brown"></button>
</form>
<div class="marker-list">
<ul>
</ul>
</div>
</div>


And Javascript code is below. Please note that there is more code and this works without filtering results for US,

inputResult = document.getElementById("search-result"),
searchBoxResult = new google.maps.places.SearchBox(inputResult),

searchBoxResult.addListener("places_changed", function () {

// Clear old markers
markers.forEach(function(place) {
place.setMap(null);
});
markers = [];

var
places = searchBoxResult.getPlaces(),
bounds = new google.maps.LatLngBounds(),
searchPlace = new google.maps.LatLng({lat: places[0].geometry.location.lat(), lng: places[0].geometry.location.lng()});

$(".search-result form").submit();

getPlacesList(searchPlace, customPlaces, searchRadius);

var placesFilter = function (element) {
return distance(element.LatLng, searchPlace) < searchRadius;
};

var j=0;
customPlaces.forEach(function (place) {
if(place.distance<=20){
createMarker(place,j++);
}
});

customPlacesFiltered = customPlaces.filter(placesFilter);

customPlacesFiltered.forEach(function(place) {
bounds.extend(place.LatLng);
});

map.fitBounds(bounds);
});


My api request is,

<script src="https://maps.googleapis.com/maps/api/js?key=xxxx&libraries=places,geometry&callback=initMap&sensor=false&libraries=geometry,places&components=country:us&ext=.js" async defer></script>


How to restrict resluts only for US using this method. Please help.

Answer

SearchBox offers fewer options than Autocomplete for restricting the search. In the former, you can bias the search towards a given LatLngBounds. In the latter, you can restrict the search to a particular country and particular place types, as well as setting the bounds.

var defaultBounds = new google.maps.LatLngBounds(
   new google.maps.LatLng(-33.8902, 151.1759), // LatLng of the north-east corner of US
   new google.maps.LatLng(-33.8474, 151.2631)  // LatLng of the south-west corner of US
);  

var input = document.getElementById('search-result');

var searchBox = new google.maps.places.SearchBox(input, { bounds: defaultBounds });

in Autocomlete we have componentRestrictions

var options = { componentRestrictions: { country: 'us' } };
var input = document.getElementById('search-result');

var autoComplete = new google.maps.places.Autocomplete(input, options);