Mastering the Google Places Autocomplete SearchBox: Managing the predictions - enabling or disabling with ease

Is there a way to manage the predictions provided by Google Places Autocomplete SearchBox (google.maps.places.SearchBox) service?

In simpler terms, can the HTML input element connected to the Autocomplete SearchBox service be temporarily disconnected and then reconnected?

The issue I am facing is that when the search results are displayed below the input element, the predictions show up over the results once the user returns focus to the input. This obstructs the view of the results and I would like to prevent predictions from showing until the user modifies the input text.

https://i.sstatic.net/GG9jY.png

EDIT 26/Aug/2016:

Currently, disabling predictions is not supported by the Javascript API. Therefore, I have submitted a feature request to Google. If you are interested in this feature, please vote for it here: Autocomplete SearchBox - Control (enable/disable) predictions..

EDIT 07/Sep/2016 - bounty award update:

Thank you to everyone who contributed answers and helped promote the question.

The main goal of the award was to find a solution using existing resources, which unfortunately did not happen, so the bounty will not be awarded.

While none of the answers below offer a solution, they do provide valuable insights that may lead to a solution in the future. Thank you! Perhaps these insights will help address the issue at hand.

The secondary goal of the award was to bring attention to the feature request for controlling predictions in the Autocomplete SearchBox. Its status has been updated to NeatIdea and has been assigned an internal tracking number, which is a positive development.

Answer №1

To enhance user experience, you can dynamically disable the autocomplete feature after a location is selected by adding a disabled class to the input field. This approach allows you to toggle the predictions based on the presence of the class.

Integrate this functionality within an if-else statement around your autocomplete code.

let field = document.getElementById('location');
if (field.className.indexOf('disabled') > -1) {
  google.maps.event.clearInstanceListeners(field);
}
else {
  let autocomplete = new google.maps.places.Autocomplete(field, {types: ['geocode']});
  autocomplete.addListener('place_changed', () => {
    let place = autocomplete.getPlace();
    let filed_val = field.value;
    field.classList.add('disabled');
  });
}

By following this structure, the autocomplete will be removed upon selecting a place. You also have the option to re-enable it by removing the disabled class from the input field whenever needed.

Answer №2

My approach using AngularJS involves extracting code from a directive.

The .pac-contained element is generated when an instance of an Autocomplete service is created, for example:

new google.maps.places.Autocomplete(…)
or
new google.maps.places.SearchBox(…)
.

What I do is locate the newly created .pac-container in the document, save its reference, and designate it as processed (by adding a custom class .predictions-control). This marking is necessary if multiple .pac-container elements may exist in the application.

With this reference, I am able to manage the visibility (hide or show) of the .pac-contained predictions.

// Code snippet to handle predictions container.
var pacContainer = null;

function getPredictionsContainer() {
    var e = document.querySelector('div.pac-container:not(.predictions-control)');
    if (e){
        var container = angular.element(e);
        container.addClass('predictions-control');
        console.log('predictions-control: Container found.');
        return container;
    } else {
        console.warn('predictions-control: Container not found!');
    }
    return null;
} 

function untilContainerFound(){
    pacContainer = getPredictionsContainer();
    if (pacContainer == null){
        $timeout(untilContainerFound, 50);
    }
}

this.init = function() {
    untilContainerFound();
};

this.hidePredictions = function() {
    if (pacContainer === null){
        pacContainer = getPredictionsContainer();
    }
    if (pacContainer){
        console.log('predictions-control: Hiding predictions.');
        pacContainer.addClass('ng-hide');
    } else {
        console.warn('predictions-control: Container not found!');
    }
}; 

this.showPredictions = function() {
    console.log('predictions-control: Showing predictions.');
    if (pacContainer){
        pacContainer.removeClass('ng-hide');
    }
}; 

Invoke init() immediately after creating the service instance:

// Creating SearchBox service for autocomplete functionality.
autocomplete = new google.maps.places.SearchBox(inputElem[0]);
// OR
// autocomplete = new google.maps.places.Autocomplete(…..);
autocomplete.addListener('places_changed', callback);

predictionsCtrl.init();

Note: It works reliably with multiple Autocomplete service instances as long as they are not created simultaneously (e.g., each service on a different tab) or the creation of the next service is delayed until the .pac-container for the previous service is located.

Answer №3

Why bother with a search box if you're not interested in predictions? Predictions are what make the SearchBox useful. If you prefer to skip predictions, consider using Text Search from the Places library.

If the user keeps interacting with the search box after receiving suggestions, they may not find the results helpful. This behavior is also seen in Google Maps and doesn't seem like a problem, right?

If you need to temporarily disable suggestions and create some space between the SearchBox and results (similar to this tool), you can destroy the existing google.maps.places.SearchBox object and recreate it later with the same HTML input element.

Answer №4

Potentially valuable insight.

This information pertains specifically to API V3.29 (though its accuracy may vary).
The autocomplete div generated by the API is assigned a class of "pac-container pac-logo".
By using document.querySelector('.pac-container'), you could potentially hide it by setting its style attribute to display: none upon clicking elsewhere on the page.

PLEASE NOTE: Google will revert the style attribute when users click back in the search box, so setting it once should be sufficient—there's no need to reset it again.
(this approach may be simpler and more organized than involving Angular).

I hope this proves useful to someone (I personally had to adjust the z-index through a CSS rule to ensure the autocomplete displayed correctly in an application).

Answer №5

Disabling predictions in a text box can be achieved by adding the disabled attribute.

It's important to note that using the readonly attribute will not have the same effect.

This feature could prove beneficial in specific situations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the error message "ReferenceError: parsePayload cannot be accessed before initialization"

Check out this code snippet: Experiencing an issue with 'ReferenceError: Cannot access 'parsePayload' before initialization' Any assistance would be appreciated const express = require("express"); const { createToDo, updateToD ...

Tracking a razor ajax form using pace.js has never been easier with these simple steps

I'm currently exploring the use of pace.js with my Razor ajax form. The form generates a Partial View upon submission. Pace.js, as per its documentation, automatically monitors all ajax requests lasting longer than 500ms without any additional configu ...

Create a function within jQuery that triggers when an option in a select field is chosen

As I edit a podcast, I have encountered a situation where an option is being selected through PHP code. Now, I am looking to implement jQuery functionality for when the option is selected from the select field. I have searched through various questions an ...

"Enhance your website with a dynamic Jssor slider featuring nested slides and vertical

Exploring the idea of merging the nested slider feature with a vertical thumbnail display. Reviewing the source code for examples image-gallery-with-vertical-thumbnail.source.html and nested-slider.source.html, I am wondering how to effectively combine t ...

What is the best way to update a BehaviorSubject holding an array without replacing the entire array?

When it comes to adding items to an array BehaviorSubject, the common practice is to assign a copy of the entire array along with the new item using next(). However, I am looking for a way to push items into this array without having to assign a full copy ...

Crafting dynamic parameters in the Express router - A step-by-step guide!

Original Code Example: const express = require('express'); const router = express.Router(); router.get('/data/:d1/:d2/:d3', require('../apifoo').foo); Route: /data/:d1/:d2/:d3 Path: /data/1/2/3 req.params : 'd1' : ...

What are the best ways to personalize my code using Angular Devextreme?

Our development team is currently utilizing Angular for the front-end framework and ASP.net for the back-end framework. They are also incorporating Devextreme and Devexpress as libraries, or similar tools. However, there seems to be difficulty in implement ...

Implementing distinct jQuery event listeners on the parent div and the button within

I am facing an issue with a button inside a list row that is used to delete the row from the page. The row is also bound to a click event that redirects to another page. This setup is causing problems as clicking the inner button triggers the containing ro ...

Difficulty in adjusting the height of the popover menu that appears when using the Select Validator in Material UI

I am having trouble adjusting the height of a popover that emerges from a select validator form in Material UI. Despite attempting various methods, including adding the following CSS to the main class: '& .MuiPopover-paper': { height: &apos ...

Displaying and Concealing Divisions

My journey to showing/hiding divs began with piecing together a series of questions: $(document).ready(function(){ $('.box').hide(); $('#categories').onMouseOver(function() { $('.box').hide(); $('#div' + ...

Issue with the message deletion feature in discord.js

I am encountering an issue with the delete function in discord.js. My code is meant to deduct 1 point from a user's balance when an image is deleted from a channel. The problem arises when I try to delete another image that I uploaded - instead of ded ...

What could be causing the issue when the selected option is being changed and the condition does not work

Whenever the selection in a select element is changed, the corresponding text should also change. Check out this Fiddle here. (function($) { 'use strict'; function updateResultText() { var s1_is_1 = $("#s1").value === '1', ...

Mapping strings to enums in Angular is an essential task that allows for seamless communication

Currently, I am facing an issue regarding mapping a list of JSON data to my model. One of the properties in my model is defined as an enum type, but in the JSON data, that property is provided as a string. How can I correctly map this string to an enum val ...

Execute the task from an external JavaScript file using npm

Utilizing node and npm as a task runner from gitbash cli has been successful for the most part. However, I am facing an issue where I am unable to call tasks in separate .js files from my package.json. Any assistance with the syntax would be greatly apprec ...

AngularJS data retrieval timeout function

After reading this response, I am currently in the process of developing a service that can provide data even if the request fails due to timing out. this.getStatus = function() { var timeoutPromise = $timeout(function () { cancele ...

What is the method to show text on hover in angularjs?

I'm a beginner in AngularJS and I'm looking to show {{Project.inrtcvalue}} when the mouse hovers over values. Can anyone guide me on how to achieve this using AngularJS? <table ng-table="tableParams" show-filter="true" class="table" > ...

Enhance Your R Shiny Leaflet with JavaScript Addons for Stunning Heat

I am currently exploring the use of a javascript addon for leaflet called the heatmap functionality, which can be found at https://github.com/Leaflet/Leaflet.heat. My goal is to integrate this feature into Shiny, however, it seems that the leaflet package ...

Is there a way to confine a draggable object's movement to a specific area?

Users have been granted the ability to input their characters onto the screen and manipulate each character's position. However, I only want users to move these characters within a specific square or rectangle area, limiting their placement options. ...

Creating a feature in Vuejs that allows for real-time card updates on the screen by sending a post request to the database and

After sending a post request to the database, I need to refresh my cardData array which gets its value from a get request in order to see the changes. The current saveDraft() function adds values to the cardData array, but it requires a page refresh or c ...

Working with NodeJS: Utilizing object casting with default values and eliminating superfluous

In the backend code of a NodeJS application, there is an object defined as follows: { name : "foo" secret : "bar" } The objective is to return this object as JSON in response to an HTTP request without including the secret key. The desired return obj ...