7 Reeds
7 Reeds

Reputation: 2559

jquery and google places autocomplete

I would like to add the Google Places address autocomplete search to a form. I see the example code HERE. I am using jquery and have my ready function in a separate js file. I have put the example functions into that external js file and it is being loaded.

I have my API key in the Google API script tag. but the callback=initAutocomplete js function is not being called.

My script section looks like -- yes, I have a real API key:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"
        integrity="..." crossorigin="anonymous"></script>

<script src="https://maps.googleapis.com/maps/api/js?key=<MY-API-KEY>&libraries=places&callback=initAutocomplete"
        async defer></script>

<script src="js/index.js'"></script>

The index.js file looks mostly like:

$(function () {
    ...

    $("#addressLookup").on('focus', geolocate());
});

var autocomplete;

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

    // When the user selects an address from the dropdown, 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();
    console.log("fillInAddress: place");
    console.dir(place);
}

// 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());
        });
    }
}

I don't see anything barfing in the js console log. I do not see the Google stuff loading in the Developer Tools "Network" panel.

What have I missed?

Upvotes: 0

Views: 1849

Answers (1)

hoang.vx
hoang.vx

Reputation: 74

I think you should change scripts order

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"
        integrity="..." crossorigin="anonymous"></script>

<script src="js/index.js'"></script>

<script src="https://maps.googleapis.com/maps/api/js?key=<MY-API-KEY>&libraries=places&callback=initAutocomplete"
        async defer></script>

Upvotes: 1

Related Questions