问题
I am trying to add an Google Geocode Autocomplete field to my form.
I have been able to get it to restrict the results returned to the country (AU) but it would be even better if I could limit the results to the state as well. (New South Wales/NSW)
This is my current initialize()
function:
function initialize() {
var options = {
types: ['geocode'],
componentRestrictions: {country:"AU"}
};
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
I have read the documentation and found that you can use the types
parameter to restrict the results, but I have been unable to work out what the exact code should be.
Simply changing it to:
types: ['administrative_area1':'NSW'], // OR 'New South Wales'
and various combinations similar to the above (= instead of : etc) have not worked..
Could someone point me in the right direction towards what the actual syntax is for what I am trying to achieve?
Thanks.
回答1:
I use autocomplete without any sort of filter on it but automatically append the state I'm interested in to all of the user input before sending the query.
For someone who wants California results, for example, if they were to search for Sacramento
it would automatically correct the input to Sacramento, California
and this has worked somewhat well for me. You could be even more specific with the data you send, for example Sacramento, California, USA
回答2:
Keep a list of state lat/long boundaries in your app and restrict autocomplete with them.
var stateBounds={
ca: ["32.812736", "-119.216815", "34.608128", "-117.039301"]
// lat/long boundaries list for states/provinces.
};
function getStateBounds(state) {
return new google.maps.LatLngBounds(
new google.maps.LatLng(stateBounds[state][0],
stateBounds[state][1]),
new google.maps.LatLng(stateBounds[state][2],
stateBounds[state][3])
);
}
new google.maps.places.Autocomplete(document.getElementById('search'), {
types: ['address'],
componentRestrictions: {country: 'us'},
bounds: getStateBounds('ca') // get LatLngBounds for ca.
});
来源:https://stackoverflow.com/questions/21871190/google-geocode-autocomplete-limit-state