Problematic search function in Google Maps API Places

I have been trying to implement the Google Maps API Places search box example into my map project.

Although both the map and the search box are visible on the page, unfortunately, when I type in the search box, nothing happens. There is no dropdown menu or autocomplete suggestions, and hitting enter doesn't trigger any search either.

Am I overlooking something crucial here?

Here is the HTML code:

<script src='//maps.google.com/maps/api/js?v=3.13&amp;sensor=false&amp;libraries=geometr‌​y,places' type='text/javascript'></script>

<input id='pac-input' class='controls' type='text' placeholder='Search'>

<div id='map_search' style='width: 100%; height: 30rem;'>

And this is the JavaScript code:

<script type='text/javascript'>
  var mapstyle = [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"transit.station","elementType":"labels.icon","stylers":[{"visibility":"on"},{"hue":"#2185d0"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]}
  ];

  function initialize() {
    var peckham = new google.maps.LatLng(51.4714, -0.0625);

    // Map search
    var map = new google.maps.Map(document.getElementById('map_search'), {
      center: peckham,
      zoom: 14,
      styles: mapstyle,
      scrollwheel: false
    });

    // Create the search box and link it to the UI element.
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function() {
      searchBox.setBounds(map.getBounds());
    });

    var markers = [];

    var infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);

    // Listen for the event fired when the user selects a prediction and retrieve more details for that place.
    searchBox.addListener('places_changed', function() {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      // Clear out the old markers.
      markers.forEach(function(marker) {
        marker.setMap(null);
      });
      markers = [];

      // For each place, get the icon, name, and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };

        // Create a marker for each place.
        markers.push(new google.maps.Marker({
          map: map,
          icon: icon,
          title: place.name,
          position: place.geometry.location
        }));

        // Show an info window
        google.maps.event.addListener(marker, 'click', function(evt) {
          service.getDetails({
            placeId: this.placeId
          }, (function(marker) {
            return function(place, status) {
              if (status === google.maps.places.PlacesServiceStatus.OK) {
                infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
                  'Place ID: ' + place.place_id + '<br>' +
                  place.formatted_address + '</div>');
                infowindow.open(map, marker);
              }
            }
          }(marker)));
        });

        if (place.geometry.viewport) {
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      map.fitBounds(bounds);
    });
  }
</script>

Answer №1

Resolved the problem.

The source of the issue was identified as an autocomplete function in another part of the code:

<script type='text/javascript'>
  function initialize() {
    var input = document.getElementById('search_address');

    var autocomplete = new google.maps.places.Autocomplete(input);
  }

  google.maps.event.addDomListener(window, 'load', initialize);
</script>

<script type='text/javascript'>
  function initialize() {
    var input = document.getElementById('listing_address');

    var autocomplete = new google.maps.places.Autocomplete(input);
  }

  google.maps.event.addDomListener(window, 'load', initialize);
</script>

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

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

Access information from multiple div elements using JavaScript data-attributes

Having trouble retrieving data-attribute values from multiple divs with the same class when clicked. The goal is to display the data value of the clicked div. function playSound(e) { const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`) ...

How to extract audio array buffer using inputBuffer.getChannelData in HTML5 Audio API

In the process of developing an application, I am working on capturing mic data from the inputBuffer and streaming it to another client for playback. However, I am encountering difficulties in getting this functionality to work properly. Although my recor ...

Show blob file as a PDF document in a popup or dialog box using HTML and TypeScript

I am currently working on integrating TypeScript and HTML to showcase the result of a webservice call as a PDF in a popup/dialog within the same page. While I can successfully open the PDF in a new tab using the window.open(url) method, I'm encounter ...

Ways to adjust the content width within an iframe without altering the iframe's overall width

I need help with adjusting the width slider in my iframe. I want the width slider to control the content width within the iframe, not the actual width of the iframe itself. Essentially, I want to switch between mobile and desktop mode by resizing the con ...

Guide on successfully importing a pretrained model in Angular using TensorFlow.js

I need help with uploading a pretrained Keras model to my existing tensorflow.js model and then making simple predictions by passing tensors in the correct format. The model is stored locally within the project, in the assets folder. export class MotionAn ...

Find unique numbers within a specified range using NodeJS

I need to update my arts on an NFT test via OpenSea API, but I'm facing an issue where the numbers are being repeated. Is there a way to select a number within a range that does not repeat? Here is my current code: const opensea = require("opense ...

What is the best way to retrieve a list of fields from a set of JSON documents?

Currently, I am facing a scenario where I have two MongoDB collections named stu_creds and stu_profile. My objective is to initially fetch all the student records from the stu_creds collection where the stu_pref_contact field corresponds to email. Subseque ...

How to extract a one-of-a-kind identification number from the browser using just JavaScript in a basic HTML file?

Is there a way to obtain a distinct identification number from a browser without resorting to techniques such as generating and storing a unique number in cookies or local storage, and without utilizing a server-side language? ...

Clear the input field for google autocomplete after a location has been selected using VueJs

I am encountering an issue with cleaning up the google autocomplete input after selecting a location. I have assigned a data value to the value prop of the component, but it seems like it is not updating. Even with a watch in place, nothing seems to be hap ...

What advantages does utilizing an angular directive provide in the context of a comment?

Up to now, I have primarily used Directives in the form of Elements or Attributes. Is the Comment style directive simply a matter of personal preference for style? app.directive('heading', [function () { return { replace: true, ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...

Press the Enter key to generate a new table row

I have been dynamically creating an HTML table. Each row contains two columns created through a recursive call. Currently, a new row is generated by clicking on the second cell, but I want to switch this action to the "Enter" key press. Although my code su ...

display angular filter for mat radio option selected from mat-radio group

On the screenshot provided below, there are 2 buttons within a mat radio group. The condition is that if modelForm.get('schedule').value equals '1', then only display the radio button with the value 'A'. Otherwise, show all va ...

Eliminating HTML elements from a string while retaining the use of ":" (colon)

Similar Question: Remove HTML Tags in JavaScript Looking for a way to eliminate HTML from a string in Javascript while preserving colons? I've checked out posts like Strip HTML from Text JavaScript and how do you strip html tags in textarea inpu ...

Issue with passing incorrect props to child component occurs specifically on pages 2 and beyond within react-table

Implementing a button in each row of a table using react-table to trigger a react-modal is functioning correctly on the initial page. However, when navigating to subsequent pages, an issue arises where the incorrect id prop is being passed into the custom ...

What is the best way to extract the elevation value (Z coordinate) from a mesh surface using X and Y coordinates in Three.js

Is there a way to determine the Z coordinate of a point in three js based on the known X and Y coordinates? I've attempted drawing a line at the X and Y points and finding the intersection with the mesh surface generated from a tiff file. However, I o ...

I'm unable to scroll back up after making an ajax request, as the code automatically scrolls to the bottom of the div

I'm currently working on implementing a JavaScript code to automatically scroll to the bottom of a div after an AJAX request is made. However, I've encountered an issue where I am unable to scroll back up because my JavaScript is constantly check ...

Extract numerical values from a specific area and manipulate them

I'm facing an issue with a field that receives its input from a list of links associated with numbers, similar to a calculator but without operators. My goal is to retrieve these numbers and divide them by 12 using a function (converting from feet to ...

Retrieve a list of all file names within a designated directory using Angular

I am working on my Angular app and I need to list all the file names inside the assets folder. To achieve this, I am planning to utilize the npm library called list-files-in-dir https://www.npmjs.com/package/list-files-in-dir Here is the service impleme ...