Search code examples
google-mapsgoogle-places-autocomplete

Limit autocomplete results within the bounds of a place_id


I have two textboxes, both of which are autocompletes. The first one we get the place_id when I change it. Second textbox is supposed to suggest results within the place_id of the first.

Here's my code:

const options = {
                    types: ['(regions)'],
                    componentRestrictions: {country: 'gb'},
                };

const search = new google.maps.places.Autocomplete(  $("#address_1")[0], options);

google.maps.event.addListener(search, 'place_changed', function () {
    var place = search.getPlace();

    const options_b = {
        types: ['(regions)'],
        componentRestrictions: {country: 'gb'},
    };

    var options_2 = {
        types: ['address'],
        strictbounds: true,
        radius:500,
        //other parameters here..perhaps place_id ?

        };

    const search = new google.maps.places.Autocomplete(  $("#address_2")[0], options_b);
});

So let's say I typed London in the first text box, then the 2nd text box should only suggest places within London.


Solution

  • If you want to limit the result of an Autocomplete to the bounds of a place, use the bounds of that place to restrict the Autocomplete and set the strictBounds: true option (note the capitalization)

    const search1 = new google.maps.places.Autocomplete($("#address_1")[0], options);
    
    google.maps.event.addListener(search1, 'place_changed', function() {
      var place = search1.getPlace();
      var bounds = place.geometry.viewport; // bounds of place returned by the first autocomplete
    
      var options_2 = {
        types: ['address'],
        strictBounds: true,
        bounds: bounds
      };
    
      const search2 = new google.maps.places.Autocomplete($("#address_2")[0], options_2);
    });
    

    proof of concept fiddle

    screenshot of resulting autocomplete

    "use strict";
    
    // This example requires the Places library. Include the libraries=places
    // parameter when you first load the API. For example:
    // <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCPJpjD-qcR_yIxJnS8maR5W9KB0E3EzYI&libraries=places">
    function initAutocomplete() {
      var map = new google.maps.Map(document.getElementById('map'))
      const options = {
        types: ['(regions)'],
        componentRestrictions: {
          country: 'gb'
        },
      };
    
      const search1 = new google.maps.places.Autocomplete($("#address_1")[0], options);
    
      google.maps.event.addListener(search1, 'place_changed', function() {
        var place = search1.getPlace();
        var bounds = place.geometry.viewport;
        var marker = new google.maps.Marker({
          position: place.geometry.location,
          map: map
        });
        var rectangle = new google.maps.Rectangle({
          bounds: bounds,
          map: map
        })
        map.fitBounds(bounds);
    
        var options_2 = {
          types: ['address'],
          strictBounds: true,
          bounds: bounds
          //other parameters here..perhaps place_id ?
    
        };
    
        const search2 = new google.maps.places.Autocomplete($("#address_2")[0], options_2);
        google.maps.event.addListener(search2, 'place_changed', function() {
          var place = search2.getPlace();
          var marker = new google.maps.Marker({
            position: place.geometry.location,
            map: map,
            icon: {
              url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
              size: new google.maps.Size(7, 7),
              anchor: new google.maps.Point(3.5, 3.5)
            }
          });
        });
      });
    }
    /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
    
    #map {
      height: 80%;
    }
    
    
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Place Autocomplete</title>
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initAutocomplete&libraries=places&v=weekly" defer></script>
      <!-- jsFiddle will insert css and js -->
    </head>
    
    <body>
      <div class="pac-card" id="pac-card">
        <div id="pac-container">
          <input id="address_1" type="text" placeholder="Enter a location" /><br/>
          <input id="address_2" type="text" placeholder="Enter a location" />
        </div>
      </div>
      <div id="map"></div>
    </body>
    
    </html>