user1032531
user1032531

Reputation: 26281

Bias google maps autocomplete using location and radius

I am trying to bias google.maps.places.Autocomplete based on location and radius (https://developers.google.com/places/webservice/autocomplete#location_biasing). The following returns results, but based on the client's IP and not my specified location. How is Google maps autocomplete properly biased for location? http://jsbin.com/nazufozeyu/1/

var autocomplete = new google.maps.places.Autocomplete(
  document.getElementById('address'), {
    types: ['geocode'],
    radius: 1000,
    location:[47.64864,-122.348927]
  }
);

Upvotes: 2

Views: 6191

Answers (2)

wholevinski
wholevinski

Reputation: 3828

So, after checking the API, it looks like the location you're providing is probably being ignored. You have options on what you can do, but you need to provide a bounds attribute in your options of type LatLngBounds. See the autocomplete options API: https://developers.google.com/maps/documentation/javascript/reference#AutocompleteOptions

You can provide a Circle, Rectangle, Polyline, etc, then pull the bounds from it. Regardless of how you do it, you need to provide a bounds of which to search in, you can't just provide a single lat-long point. @user1032531 provided a good example of how you might do it with a circle.

If you have a certain city/country in mind you want to search in, you can use the geocoding API: https://developers.google.com/maps/documentation/geocoding/

Call the API like this: https://maps.googleapis.com/maps/api/geocode/json?address=Toledo&key=API_KEY and you'll get some JSON back that has a "bounds" key. Take your boundbox, and pass it to the places API call.

Upvotes: 1

user1032531
user1032531

Reputation: 26281

I am sure this could be done better, but the following will work. http://jsbin.com/vetayoreto/1/

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>google.maps.places.Autocomplete</title>  
        <style type="text/css">
            input{width:600px; display:block;}
        </style> 
        <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;libraries=places"></script>
    </head>
    <body>
        <input id="input" type="text" value="" />
        <script>
            var center = new google.maps.LatLng(40.7,-74);
            var circle = new google.maps.Circle({
                center: center,
                radius: 10000
            });
            var autocomplete5 = new google.maps.places.Autocomplete(
                document.getElementById('input'),
                {
                    types: ['geocode']
                }
            );
            autocomplete5.setBounds(circle.getBounds());
        </script>
    </body> 
</html> 

Upvotes: 4

Related Questions