本文介绍了Google Maps API找不到$(document).ready中定义的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Jquery和Google Maps API时遇到问题.

I have a problem with Jquery and Google Maps API.

脚本似乎在html中正确定位

Scripts seem to be located correctly in html

<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/main.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

问题在于init映射位于$(document).ready

The problem is that init map is inside $(document).ready

$(document).ready(function () {
    let url = "ws://localhost:61614/";
    let topic = "stomp.topic";
    let client;

    let map, trackers = {};

    $("#connect_button").click(function () {
        connect(url);
        return false;
    });

    $("#disconnect_button").click(function () {
        disconnect();
        return false;
    });

    function initMap() {
        let mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(30, 0),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map"), mapOptions)

    }
}

必须如何正确访问initMap?

How correctly initMap must be accessed ?

推荐答案

我认为您忘记了调用initMap函数.

I think you forgot to call initMap function.

尝试一下- https://jsitor.com/227rClFCE

脚本路径https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap中的回调将查找全局方法名称initMap,但是它不是全局定义的,并且在document.ready范围内具有作用域,因此它将不执行.要么在document.ready回调内部调用方法,要么在initMap函数下面执行Window.initMap = initMapWindow对象内部添加此方法.

The callback in scripts path https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap will look for global method name initMap, however it is not defined globally and scoped inside document.ready scope so it won't execute. Either call the method inside document.ready callback or else after add this method inside Window object by doing Window.initMap = initMap below initMap function.

这篇关于Google Maps API找不到$(document).ready中定义的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 15:00