jquery和谷歌地方自动完成

时间:2018-01-05 01:59:46

标签: javascript jquery google-places-api

我想将Google商家信息地址自动填充搜索添加到表单中。我看到示例代码HERE。我正在使用jquery并将我的ready函数放在一个单独的js文件中。我已将示例函数放入外部js文件中并正在加载。

我在Google API script标记中有我的API密钥。但是没有调用callback=initAutocomplete js函数。

我的脚本部分看起来像 - 是的,我有一个真正的API密钥:

<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>

index.js文件看起来很像:

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

我在js控制台日志中看不到任何关于barfing的事情。我没有在开发者工具&#34;网络&#34;中看到谷歌的东西加载面板。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

我认为您应该更改脚本顺序

<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>