How to set a default value for a Google places API auto complete textbox

后端 未结 2 902
心在旅途
心在旅途 2021-02-14 18:41

I\'m working on a page close enough to the one in google samples https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform and it work

2条回答
  •  逝去的感伤
    2021-02-14 19:46

    I came across this post while trying to solve for a similar use case (populating the Autocomplete with the last place a user searched for).

    As far as I can tell it is not possible to set a default for the Autocomplete that it recognises as a place. However, I think you can simulate this effect using the Autocomplete Service (example - also see the reference sections on #AutocompletePrediction and #PlacesService):

    • Set your Autocomplete to the identified city and country as you are already
    • Pass the city and country to the Autocomplete Service
    • Determine the place ID of your preferred prediction (e.g. select the first prediction with type = 'city')
    • Use the Places Service to get the details (PlaceResult) for your chosen place ID (same result as using autocomplete.getPlace())
    • Have a callback that does what you need with the PlaceResult

    This gives your user the impression that the Autocomplete is in use. If the result is what they need, great! If they want to search for a different place set up your autocomplete to listen for place_changed and run autocomplete.getPlace() followed by the same callback.

提交回复
热议问题