What is the correct way to completely remove GoogleMaps autocomplete?

I am using GoogleMap v3 AutoComplete and I need to completely remove it and disable all event listeners. My code for initializing and binding to events is as follows:

var autocomplete = new google.maps.places.Autocomplete($("input").get(0), { types: ["geocode"] }); google.maps.event.addListener(autocomplete, 'place_changed', function () { // handle events }); 

I do not see an official way to correctly delete autocomplete and cancel all events. Please indicate me the correct path.

Thanks.

+5
source share
1 answer

To unleash events, use google.maps.event.clearInstanceListeners .

There is no implemented method to remove autocomplete functionality. You can create an input clone before creating Automplete, and when you want to remove autocomplete functionality, replace the current input with a clone.

 //-------------------------------------------------------------- //this overides the built-in Autocomplete and adds a remove-listener //execute it once when the API has been loaded (function(ac) { google.maps.places.Autocomplete = function(node, opts) { var clone = node.cloneNode(true), pac = new ac(node, opts); google.maps.event .addListener(pac, 'remove', function(restore) { google.maps.event.clearInstanceListeners(pac); google.maps.event.trigger(node,'blur'); google.maps.event.clearInstanceListeners(node); if (restore===true) { node.parentNode.replaceChild(clone, node); } else { node.parentNode.removeChild(node) } }); return pac; } } (google.maps.places.Autocomplete)); //-------------------------------------------------------------------------- function initialize() { autocomplete = new google.maps.places .Autocomplete(document.getElementsByTagName('INPUT')[0], { types: ["geocode"] }); } google.maps.event.addDomListener(window, 'load', initialize); 
 <script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&.js"></script> <input/> <span> <input type="button" value="remove input" onclick="google.maps.event.trigger(window.autocomplete,'remove'); this.parentNode.parentNode.removeChild(this.parentNode);"/> <input type="button" value="remove autocomplete-functionality" onclick="google.maps.event.trigger(window.autocomplete,'remove',true); this.parentNode.parentNode.removeChild(this.parentNode);"/> <span> 

The script adds remove-listener to Automplete. The listener takes a single argument. Set to true when you want to remove autocomplete functionality. Otherwise, the input will be completely deleted.

+8
source

All Articles