Site icon Hip-Hop Website Design and Development

Maps search box autocomplete with callback JS function?

I am struggling with using a callback for my Google Maps API.
I am trying to have a Goolge Maps autocomplete search box and collect the Lat and Long for the searched location. I’ve found this answer that works really well, but sometimes the search box won’t load the location suggestions. I’ve found that this might be caused by the google.maps.event.addDomListener(window, 'load', initialize); that I use. Instead I’ve found that I need to use a callback in my script. I tried that but now the search box won’t load any suggestions anymore. Below is what I have now. Am i doing something wrong? Thanks a million for your help and suggestions!

In functions.php

<?php
//ENQUE SCRIPTS
function my_enqueue() {
    // First register script
    // Google maps API
    wp_register_script('googlemaps', 'https://maps.googleapis.com/maps/api/js?key=XXXXXX&libraries=places&callback=initialize');
    wp_register_script( 'ajax-script', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery') );
    
    // Then enqueue script
    wp_enqueue_script( 'googlemaps' ); 
    wp_enqueue_script( 'ajax-script' ); 
  }
  add_action( 'wp_enqueue_scripts', 'my_enqueue' );
?>

In custom.js

jQuery( document ).ready(function($) {
    function initialize() {
        var input = document.getElementById('searchTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);
          google.maps.event.addListener(autocomplete, 'place_changed', function () {
              var place = autocomplete.getPlace();
              if (!place.geometry) {
                window.alert("Select a suggestion from the list");
                return;
              }

              document.getElementById('city2').value = place.name;
              document.getElementById('cityLat').value = place.geometry.location.lat();
              document.getElementById('cityLng').value = place.geometry.location.lng();
          });
      }
      //Window load does not seem to always work?
      //google.maps.event.addDomListener(window, 'load', initialize);
}); //Close document ready

In html

<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />