Mitro
Mitro

Reputation: 1260

Google Maps v3 - Limit area where a function can work

In my javascript code using Google Maps API v3 I tried to set bounds to the Autocomplete function, it works quite well infact as soon as I type a letter in the input field (html), the same autocomplete advise me with addresses that can be found in the bounds area, however if I type the name of a city that is outside bounds limit I get advice also for that and other cities. Is there a way to avoid this? I'd like to have only advice for my "bounds".

Here is the piece of code:

init = function() {

    var latlng = new google.maps.LatLng(40.635636, 17.942414);
    var mapOptions = { zoom: 13, center: latlng, minZoom: 10, maxZoom: 16};

    default_bounds = new google.maps.LatLngBounds();    
    default_bounds.extend(new google.maps.LatLng(40.635636-0.33, 17.942414-0.33));
    default_bounds.extend(new google.maps.LatLng(40.635636+0.33, 17.942414+0.33));

    console.log("Initialing map at: 40.635636, 17.942414");

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    originAutocomplete = new google.maps.places.Autocomplete(document.getElementsByName("origin")[0], {types: ['geocode']});
    destinationAutocomplete = new google.maps.places.Autocomplete(document.getElementsByName("destination")[0], {types: ['geocode']});

    originAutocomplete.setBounds(default_bounds);
    destinationAutocomplete.setBounds(default_bounds);

}

Correct image: (show only places in Puglia south Italy) correct image Incorrect image: (show places of many different regions) Incorrect

Upvotes: 0

Views: 215

Answers (1)

kaho
kaho

Reputation: 4784

According to the documentation, there are 4 ways to set biases and search-area boundaries for Autocomplete, and they are
* Set the bounds on creation of the Autocomplete object.
* Change the bounds on an existing Autocomplete.
* Set the bounds to the map's viewport.
* Restrict the search to a specific country.

Since the first 3 options would only bias, but not restrict the result, you can only filter out other country's information, but not cities from the same country.

Note that you might able to modify the result by playing with the return object, but that is a violation of the ToS.

Upvotes: 1

Related Questions