在 Ajax 回调中使用 Google 地图变量



为什么map变量在ajax回调函数(成功)中无法访问,而其他变量可以访问。

为了进一步解释我的问题,我在以下代码中添加了注释

var map;
var g = 10;
function initialize() {
    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(-34.397, 150.644)
    };
    map = new google.maps.Map(document.getElementById('map_el'), mapOptions);
    g = 15;
    alert(g); // Gives 15
    alert(map.getCenter()); // Gives correct values
}

但是在下面的函数中,在 ajax 回调请求中。我面临有线响应

$(document).ready(function ()
{
    initialize();            
    $.ajax({
        url: 'ajax.aspx/getLocation',
        type: "POST",
        contentType: "application/json; charset=uft-8",
        dataType: 'json',
        success: function (data)
        {
            alert(g); // Gives 15
            alert(map.getCenter()); // Gives error => map is undefined
        }
    });
});

注意:上述两个函数在脚本标记中处于同一范围内

您的initialize函数似乎正在执行asynchronously . 因此,请尝试使用类似setTimeout()进行具有少量时间延迟的 ajax 调用

$(document).ready(function () {
    initialize();            
    setTimeout(function () {
        $.ajax({
            url: 'ajax.aspx/getLocation',
            type: "POST",
            contentType: "application/json; charset=uft-8",
            dataType: 'json',
            success: function (data)
            {
                alert(g); // Gives 15
                alert(map.getCenter()); // Gives error => map is undefined
            }
        });
    }, 10);
});

或与callbacks.

最新更新