Input Field: Address Autocomplete with Google Maps in Editor X

Wix Editor has a nice feature that allows you to have Google Place Autocomplete using Address Input .

This feature allows Google to autocomplete any address the visitor may enter in the Input Field.

But this feature is not available in Editor X based on this official post yet.

I searched many websites and many code snippets but none of them worked well in the way that I wanted. So, I decided to write my own code with my own taste and work-around. Below is the final output of this tutorial:


To be able to continue this tutorial, first, you have to:


To add and set up your Input Field:

  1. Click Add Element on the top side of Editor X.

  2. Click Input .

  3. Click Text Input .

  4. Choose one of the styles available.


To add and set up your Prediction Layout:

  1. Click Add Element on the top side of Editor X.

  2. Click Layout Tools .

  3. Click Repeaters .

  4. Choose the first Repeater Layout (columnar Layout)


Touchups

To make it a little bit nicer in a way that it looks like an Address input, follow the below steps ( also you can check the video for better understanding ):

  1. Select the repeater and using Manage Items, remove all the items, and just keep 1 item .

  2. Select the repeater and click Change Layout and then in the Display Type select List and Vertical margins=0 .

  3. Add a Text Field to the Repeater and make it’s width=%100 .

  4. Select the only item in the Repeater and remove the Min H and make it none .

  5. Bring the repeater below the text field and select the same Width for both the repeater and text field .

  6. Select the repeater and the text field and click Stack .

  7. From the top menu click View and select Code Properties .

  8. Select the repeater and form Properties menu, select Collapsed on load .

  9. A few touchups to make a pleasant component.


Cautious
Use Code Properties to make sure the ID of all properties is like the below list so the next section and the codes can work for you without any change. Otherwise, do the changes accordingly:

  • Input Field → ID: inputAddress

  • Repeater → ID: repeaterSuggestions

  • Input Field → ID: text1


Backend Code

The below code uses Google AutoComplete HTTP API to fetch the information about the address that the user writes in the input field and will return the array of suggestions for the address:

import { fetch } from 'wix-fetch';
const key = "YOUR_API_KEY";

// returns a list of place "suggestions" based on the user input
const apipart1 = "https://maps.googleapis.com/maps/api/place/autocomplete/json?";
const apipart2 = "&key=";
export function autocomplete(string) {
 let input = "input=" + string;
 let url = apipart1 + input + apipart2 + key;
 return fetch(url, { method: 'get' }).then((httpResponse) => {
 if (httpResponse.ok) {
 return httpResponse.json();
        }
    });
}

To use the above code you should create a Web Module using the below steps:

  1. Click Site Structure on the top side of Editor X.

  2. Click Backend and then click on the Plus (+) sign to add a New Web Module and name it gmapsapi.jsw

  3. Copy the code mentioned above and replace YOUR_API_KEY with the API Key you generated in the first step.


Frontend Code

To utilize the code we wrote in the backend and integrate it with the elements in the frontend, we have to:

  1. Add input_event to the input field

  2. Add itemReady_event to the repeater

We should add the first event handler to the input field so anytime the user writes something in the field, it reacts to the input and fetch the new suggestions.
Then, we will assign these suggestions to the repeater using itemReady event.

Utility Function
The below code is a utility function that will generate a random string value with a defined length. The default value for the length is 10:

function getRandStr(length = 10) {
 return Math.random().toString(20).substr(2, length)
}

We need to use this function in the Input Field in the next section.
Tip: Each item in the repeater needs a unique id, this is the reason we generate a random string to use it as the unique id for each suggestion.

Input Field
The below code will call the autoComplete() function we have in the backend to fetch the new suggestions:

 autocomplete($w('#inputAddress').value)
        .then((res) => {

 let predictions = res.predictions; // For simplicity we put the predictions in a new variable
 let suggestions = []; // We should create an empty array for the suggestions
            predictions.forEach(function (prediction) {
 let item = { "_id": getRandStr(), "address": prediction.description };
                suggestions.push(item);
            });
            $w("#repeaterSuggestions").data = []; // clear the repeater contents
            $w("#repeaterSuggestions").data = suggestions; // add the new suggestions to the repeater
            $w("#repeaterSuggestions").expand(); // Repeater is full now, let's show it.
        })

To use the above code we have to assign it to the input field using the below steps:

  1. Select the input field.

  2. In the Properties menu, click on the Plus (+) sign in front of onInput and press enter.

  3. The below code will appear in the Code Editor area then, add the code mentioned above:

export function inputAddress_input(event) {
 // Add your code for this event here: 
}

Repeater
In this section, we assigned the suggestion data to the repeater. But it is just raw data, now we have to decide about it and assign the text to the text field in the repeater.
Also, we have to add an onClick_event to the text field in the repeater to:

  1. Set the selected text to the text field

  2. Collapse the repeater

This code will help us to do this:

$item("#text1").text = itemData.address;

    $item("#text1").onClick((event) => {
        $w('#inputAddress').value = $item("#text1").text
        $w('#repeaterSuggestions').collapse()
    });

To achieve this, let’s follow these steps:

  1. Select the repeater.

  2. In the Properties menu, click on the Plus (+) sign in front of onItemReady and press enter.

  3. The below code will appear in the Code Editor area then, add the code mentioned above:

export function repeaterSuggestions_itemReady($item, itemData, index) {
 // Add your code for this event here: 
}

Now it is the time to publish the website and enjoy your work.


I hope you enjoyed this tutorial.
Please comment below for any suggestions.
datagit.ir

5 Likes

Hello! You forgot to add:

import {autocomplete} from ‘backend/gmapsapi’ ;

On the frontend code

Good work Massoud! Is it also possible to get the latitude/longitude form the clicked address?

Hey @massoudmaboudi

I’m fairly new to Velo by Wix, and coding in general, so please bear with me here. My code is not recognizing “$item”. It almost seams as if we need to define “$item” by using language such as “let $item ( “#text1” ). text = itemData . address”, correct? But then, Velo is also not recognizing “itemData”. I’ve attached a snippet of my entire front end code. I added the line “import (autocomplete) from ‘backend/gmapsapi’” like @melissa-hong suggested,
which helped satisfy the unknown “autocomplete” variable. Could someone please help direct me? Thanks!


Put the whole code snippet below repeaterSuggestions_itemready into that function

Thanks, that certainly fixed the issue on hand. I also moved the autocomplete code into the inputAddress_input event. Is this correct? I’m afraid the overall function still is not working on the live site, despite there being no errors.


#inputAddress=input4
#repeaterSuggestions=repeater1
#text1=input9
@melissa-hong

Thank you very much for this - I was trying to figure it out and I finally got it to work thanks to your help.

I’m having one issue though: the data collection my input field is connected to is only receiving the letters that I initially put in the input field, rather than what’s added after Google makes the suggestion. So if I typed “san f…” and Google populated San Francisco, CA, USA; I’m still only seeing “san f” in the collection. I’ve basically used the exact same code that you’ve posted. Do you have any suggestions to fix this?

Fixed - found the info “If an element is connected to a dataset, setting the element’s value in code does not set the value of the connected field in the dataset. That means if you use the dataset to perform a submit, the value changed in code is not reflected in the submitted item.” (https://www.wix.com/velo/forum/coding-with-velo/dynamically-prepopulated-form-field-is-not-saved-unless-changed)

Added setFieldValue() to submit button click:
export function submit_click ( event ) {
$w ( “#dataset2” ). setFieldValue ( “location” , $w ( ‘#location’ ). value );
}

…which worked. In case anyone else is having the same issue. Thanks again!

Thanks for this, it’s been really helpful for what I’ve needed.
My problem is slightly different, in that I’m using a different external API (not Google) to get address details, then displaying them in the repeater. The API I’m using returns 3 fields - address, city and postal code. I’m displaying this in the repeater text like so (using basic javascript):
address, city, postal code
However, when the user selects an option from my repeater dropdown, I want three different inputs to be populated - one with the address, one with the city, one with the postal code. Currently, it’s putting all of that text ( address, city, postal code) into the “Address” input and the other two are blank.
Any ideas how I can get this to work?

Need video of this!