【问题标题】:jquery and google places autocompletejquery 和 google 地方自动完成
【发布时间】:2018-01-05 01:59:46
【问题描述】:

我想将 Google 地方信息地址自动完成搜索添加到表单中。我看到了示例代码HERE。我正在使用 jquery 并将我的准备好的函数放在一个单独的 js 文件中。我已将示例函数放入该外部 js 文件并正在加载。

我的 API 密钥在 Google API script 标记中。但是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 控制台日志中看不到任何内容。我没有在开发者工具的“网络”面板中看到加载 Google 的内容。

我错过了什么?

【问题讨论】:

    标签: javascript jquery google-places-api


    【解决方案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>
    

    【讨论】:

    • 谢谢@hoang。那是个好主意……不是答案,而是个好主意。我最终使用了 jquery getscript() 方法。现在它正在工作
    • 幸运的是它帮助了你。伟大的! ^.^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 2015-05-30
    • 1970-01-01
    • 2015-03-22
    • 2016-04-30
    • 2015-02-07
    • 2015-07-17
    相关资源
    最近更新 更多