26

Here is my issue: I am using Google Places Autocomplete to gather information about places from the user.

On the event "place_changed", I save this information. However I want to give the user the possibility to add multiple places. So after this place has been save I want to clear the input.

However Google Autocomplete automatically replace the last entry in the input field. Anyway to get rid of that?

The details :

var inputDiv = $('#myinput');
var options = {
  types: ['(cities)']
};
var autocomplete = new google.maps.places.Autocomplete(inputDiv[0], options);

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var places = autocomplete.getPlace();
    savePlaces(places);

    console.log(inputDiv.val()); // 'Paris, France'
    inputDiv.val('');
    console.log(inputDiv.val()); // (an empty string)

    setTimeout(function() {
        console.log(inputDiv.val()); // 'Paris, France' (It's back!)
        inputDiv.val('');
        console.log(inputDiv.val()); // (an empty string)      
    }, 1);

    setTimeout(function() {
        console.log(inputDiv.val()); // (an empty string)      
    }, 10);
}

You will tell me, well that looks fine, just clear it in the timeout. BUT when I click away from the input (it loses the focus). The last entry comes back again!

Any idea to fix that? I haven't found in the Google documentation a function such as

autocomplete.clear();

Thanks!

7 Answers 7

19

It appears that the autocomplete internally listens to the blur-event of the input, so lets give it something to listen for and clear the field after that:

inputId_div.blur();    
setTimeout(function(){
 inputId_div.val('')
 inputId_div.focus();},10);
9
  • 1
    Well it does work! Altough it's quite a hack =) The only problem is that it "flashes" the autocomplete dropdown during a fraction of a millisecond.
    – Tristan
    Jan 18, 2013 at 9:38
  • 1
    Yes, I've seen that. But the only other option I found was to replace the input with a new input and create a new autocomplete, Im afraid this creates memory-leaks. You may try to set the visibility of the input to "hidden" at the begin and back to "visible" at the end.
    – Dr.Molle
    Jan 18, 2013 at 10:04
  • Mm you can't focus on a hidden input though.
    – Tristan
    Jan 18, 2013 at 10:51
  • Sorry, I don't mean the input, I mean the dropdown $('.pac-container')
    – Dr.Molle
    Jan 18, 2013 at 10:55
  • I tried but Google doesn't let you hide it, it brings it back automatically! It's a pity they don't have a method to clear that cleanly without having to go though all this.
    – Tristan
    Jan 18, 2013 at 11:12
13

to clear place you can use :

autocomplete.set('place',null);

it triggers place_change event too.

1
  • 2
    IMO this is the best solution.
    – artemisian
    May 2, 2018 at 18:05
11

The previous term persists in the autocomplete object.

Solution: Clear the input box then create a new autocomplete object. Also be sure to remove previous event listeners.

Declaration:

var input = document.getElementById('autocomplete');
var autocomplete;
var autocompleteListener;
var onPlaceChange = function() {...};

var initAutocomplete = function() {
  autocomplete = new google.maps.places.Autocomplete(input);
  autocompleteListener = google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChange);
};

To clear:

input.value = "";
google.maps.event.removeListener(autocompleteListener);
initAutocomplete();

The previous autocomplete object should be garbage collected. Please correct me if I'm wrong. To be sure you are exposing memory leaks, you can manually delete it.

1
  • IMO this is the right way to solve the problem, thanks! Jun 10, 2015 at 19:39
2

Not sure if this problem is still around but I found a fix that worked for me

google.maps.event.addListener(autoComplete, 'place_changed', function() {   
   $this.one("blur",function(){
      $this.val("");
   });

   //[DO YOUR CODE HERE]

   setTimeout(function(){
      $this.val(""); 
   },10); 
});

$this is a jQ reference to the autocomplete field. The blur event will trigger when you type in your value and tab into the autocomplete list and hit enter. When you click somewhere with the mouse, the blur event will trigger and clear the field.

If you use mouse directly after typing to select result, the blur is not triggered. Then the timeout will remove the value from your field.

It seems like a ridicolous hack to clear the field after input but I spent 4 hours searching the net and looking though the api of google and couldnt find a better solution.

0
import React, { useRef } from 'react';
import { Autocomplete } from '@react-google-maps/api';

const MyComponent = () => {
const autoCompleteInputRef = useRef();

const clearAutoCompleteInput = () => {
  const allInputs = 
    autoCompleteInputRef.current.querySelectorAll('input');
  allInputs.forEach(singleInput => singleInput.value = '');
}

return (
  <Autocomplete>
    <TextField
     label="Place to see"
     ref={autoCompleteInputRef}
   />
 </Autocomplete>
)
}
1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Aug 17, 2023 at 11:57
-1

As a slight enhancement to Dr.Molle's excellent answer you can use the z-index property to work around the flash, at least in recent browsers:

var input = $('#[id of autocomplete field]');
$(input).blur();
setTimeout(function() {
    var container = $('.pac-container');
    var zIndex = $(container).css('z-index');
    $(container).css('z-index', -1);
    input.val('')
    input.focus();
    setTimeout(function() {
        $(container).css('z-index', zIndex);
    }, 200);
}, 10);
-4

Try:

document.getElementById('myinput').value = '';

or

inputId_div.value = '';

I am not sure why you're using inputId_div[0]. I guess it must be a jQuery thing.

3
  • Yes I use inputId_div[0] just because I prefer using jQuery in general.
    – Tristan
    Jan 17, 2013 at 17:06
  • @Tristan, right but what is the variable pointing to the input field? inputId_div[0] would suggest that inputId_div is an array, where it should be a scalar. (I never used jQuery).
    – Marcelo
    Jan 17, 2013 at 17:24
  • inputId_div[0] in jQuery's var inputId_div = $("#myinput"); is the equivalent of inputId_div in JavaScript's var inputId_div = document.getElementById(inputId);
    – Tristan
    Jan 17, 2013 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.