Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

javascript - How can we restrict google map autocomplete to only a particular city?

My requirement is to get google places autocomplete suggestion only for the places in Bangalore, but if I search for any other place apart from bangalore then also I get the suggestions which I don't want. I have found many stackoverflow links related to my question but none of them are solving my problem.

Is this possible to get the suggestions of any particular city ?

I am sharing my code below :-

var input = (document.getElementById('address'));
          var s_w = new google.maps.LatLng( 12.97232, 77.59480 ); //southwest
          var n_e = new google.maps.LatLng( 12.89201, 77.58905 ); //northeast
          var b_bounds = new google.maps.LatLngBounds( s_w, n_e ); //bangalorebounds

var options = {
            bounds:b_bounds,
            componentRestrictions: {country: "in"}
           };
var autocomplete = new google.maps.places.Autocomplete(input, options);

autocomplete.bindTo('bounds', map);

autocomplete.addListener('place_changed', function() {

  //rest_of_the_code

});

Please somebody help !!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try like this.

var bangaloreBounds = new google.maps.LatLngBounds(
   new google.maps.LatLng(12.864162, 77.438610),
   new google.maps.LatLng(13.139807, 77.711895));

var autocomplete = new google.maps.places.Autocomplete(this, {
   bounds: bangaloreBounds,
   strictBounds: true,
});

autocomplete.addListener('place_changed', function () {

});

Note: The URL should be: https://maps.googleapis.com/maps/api/js?libraries=places&key=YOUR_API_KEY

strictBounds option was added in version 3.27 of Maps JavaScript API which is currently (January 2017) the experimental version.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...