Hello everyone,
I’m trying to add a Google standalone search dropdown to an input field in Builder.io, but I’m having some trouble integrating it. I want users to see Google address search suggestions as they type into the input field, similar to the experience in Google’s own search bar.
Could anyone guide me on how to achieve this within Builder.io? Is there a specific plugin or script that needs to be added? Any help or examples would be greatly appreciated!
Thank you!
Hello @zahanwasif,
To integrate a Google address search dropdown into an input field within Builder.io, you can use the Google Places Autocomplete API. This API provides address suggestions as the user types, similar to Google’s search bar.
Here’s a general approach to achieving this:
1. Get a Google Places API Key
- You need to have a Google Cloud project and enable the Places API.
- Obtain an API key from the Google Cloud Console.
2. Add the Google Places Script
- You’ll need to add the Google Places API script to your Builder.io project. You can do this by adding a custom script in the Builder.io page settings or directly in the custom code field.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
Replace YOUR_API_KEY
with the actual API key.
3. Add the Input Field in Builder.io
- Drag and drop an input field component where you want the search functionality.
- Give it an ID, for example,
address-input
.
4. Initialize the Autocomplete
- You need to initialize the Google Places Autocomplete on your input field. You can do this using a custom JavaScript snippet within Builder.io’s custom code section.
function initAutocomplete() {
const input = document.getElementById('address-input');
const autocomplete = new google.maps.places.Autocomplete(input, {
types: ['geocode'], // You can restrict results to certain types
});
// Optionally, you can add event listeners to handle selection
autocomplete.addListener('place_changed', function() {
const place = autocomplete.getPlace();
console.log(place);
});
}
// Make sure to call initAutocomplete when the page is ready
window.onload = initAutocomplete;
5. Optional: Customize the Autocomplete Behavior
- You can restrict the suggestions to specific types (e.g., addresses, cities).
- Use the
componentRestrictions
option to limit results to a particular country.
6. Publish and Test
- Once the setup is complete, publish your changes in Builder.io and test the functionality to ensure it works as expected.
This approach should help you integrate the Google Places Autocomplete into your Builder.io input field. If you need more advanced features or face any issues, feel free to ask!