Places API Autocomplete Form Fields Not Working

2019-08-18 22:25发布

I've created a test file on my WordPress website to try an figure out and learn the Google Maps Api with the Places Library. There is a lot of questions about different issues regarding Google Maps API on SO but i've yet to find an answer that fix my problem.

I get uncaught error messages for setbounds(), and if I try to adjust the code it only throws another error like "google is not defined", "geolocate is not defined" and so on, it is a never ending stream of errors.

Needless to say, my experience with javascript is very limited, to the point of simple "show()" "hide()" functions and nothing else. So I am having a hard time debugging this.

I've copied the exact code from https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform. I'll add my code so you can see how it looks and hopefully help with the answer.

Note 1: I have added separate script tags for the maps api places library and jQuery in the file it self just to see if it made a difference, but then it just conflicted with my enq Maps script in the functions.php file. If I comment out the enq script in functions.php and only use the "script src" in the file/page it throws the same errors as it did with enq scripts.

Note 2: I've also tried wrapping the JS inside "script src (maps api)" tag, which resulted in no change at all, the same errors thrown either way.

What's working and what's not: Nothing works, the autocomplete form field throws different undefined erros when clicked and does not provide any autocomplete dropdowns.

My code:

functions.php (enqueue script)

    wp_enqueue_script('googleMap', '//maps.googleapis.com/maps/api/js?key=KEY&libraries=places', NULL, '1.0', true);

page-custom.php (Markup)

<form>
    <div class="form-group">
                    <input type="text" class="form-control" id="autocomplete" placeholder="Search Address" onFocus="geolocate()">
    </div>
    <div class="form-group">
                    <input type="text" class="form-control" id="route" placeholder="Street" disabled>
    </div>                    
    <div class="form-group">
                    <input type="text" class="form-control" id="street_number" placeholder="Nr" disabled>
    </div>                    
    <div class="form-group">
                    <input type="text" class="form-control" id="postal_code" placeholder="Zip" disabled>
    </div>                    
    <div class="form-group">
                    <input type="text" class="form-control" id="locality" placeholder="City" disabled>
    </div>
    <div class="form-group">
                    <input type="text" class="form-control" id="administrative_area_level_1" placeholder="County" disabled>
    </div>
    <div class="form-group">
                    <input type="text" class="form-control" id="country" placeholder="Country" disabled>
    </div>
</form

page-custom.php (JS "placed underneath markup")

<script>
    // This sample uses the Autocomplete widget to help the user select a
    // place, then it retrieves the address components associated with that
    // place, and then it populates the form fields with those details.
    // This sample requires the Places library. Include the libraries=places
    // parameter when you first load the API. For example:
    // <script
    // src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

    var placeSearch, autocomplete;

    var componentForm = {
      street_number: 'short_name',
      route: 'long_name',
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      country: 'long_name',
      postal_code: 'short_name'
    };

    function initAutocomplete() {
      // Create the autocomplete object, restricting the search predictions to
      // geographical location types.
      autocomplete = new google.maps.places.Autocomplete(
          document.getElementById('autocomplete'), {types: ['geocode']});

      // Avoid paying for data that you don't need by restricting the set of
      // place fields that are returned to just the address components.
      autocomplete.setFields('address_components');

      // When the user selects an address from the drop-down, populate the
      // address fields in the form.
      autocomplete.addListener('place_changed', fillInAddress);
    }

    function fillInAddress() {
      // Get the place details from the autocomplete object.
      var place = autocomplete.getPlace();

      for (var component in componentForm) {
        document.getElementById(component).value = '';
        document.getElementById(component).disabled = false;
      }

      // Get each component of the address from the place details,
      // and then fill-in the corresponding field on the form.
      for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType]) {
          var val = place.address_components[i][componentForm[addressType]];
          document.getElementById(addressType).value = val;
        }
      }
    }

    // Bias the autocomplete object to the user's geographical location,
    // as supplied by the browser's 'navigator.geolocation' object.
    function geolocate() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          var circle = new google.maps.Circle(
              {center: geolocation, radius: position.coords.accuracy});
          autocomplete.setBounds(circle.getBounds());
        });
      }
    }
</script>

If I remove all of the JS and place this code snipped I found in a question relating to something else here on SO, I get the autocomplete address search input to work, but that code snippet has only that function, it does not populate any of the other fields.

Here is the working snippet (Address search only)

<script>
jQuery(document).ready(function ($) {
    $(function(){
      var autocomplete;
      var geocoder;
      var input = document.getElementById('autocomplete');
      var options = {
        types: ['geocode']
      };
      autocomplete = new google.maps.places.Autocomplete(input,options);
    });
});
</script>

Hoping someone here on SO can help with this, as I am lost as to what to do, to get this working.

0条回答
登录 后发表回答