简体   繁体   English

如何加载谷歌地图作为回调?

[英]How to load google maps as callback?

I have defined an ajax function that get some records from the database, after the data was taken I want load google maps, so I passed the function as callback: 我定义了一个ajax函数,该函数从数据库中获取一些记录,在获取数据后,我想加载google maps,因此我将该函数作为回调传递:

get_records = function (callback) {
    var postUrl = "someurl";
    var postData =
    {
        csrfToken: "token",
    };

    $.post(postUrl, postData, function (response) {
        callback(response);
    });
};

this is the callback: 这是回调:

get_records(function(result){
    init_map();
});

where init_map is: 其中,init_map是:

init_map = function () {

    var map;

    google.maps.event.addDomListener(window, "load", function () {

        map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(33.808678, -117.918921),
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var infoWindow = new google.maps.InfoWindow();

        function createMarker(options, html) {
            var marker = new google.maps.Marker(options);
            if (html) {
                google.maps.event.addListener(marker, "click", function () {
                    infoWindow.setContent(html);
                    infoWindow.open(options.map, this);
                });
            }
            return marker;
        }

        var marker0 = createMarker({
            position: new google.maps.LatLng(40.9117877, 14.7679659),
            map: map,
            icon: "../assets/img/marker-green.png"
        }, "<h1 class='black-content'>Marker 0</h1><p>This is the home marker.</p>");
    });

    return map;
};

if I place the init_map function outside get_records the map is displayed, but with the code above I get no map displayed, why? 如果我将init_map函数放置在get_records之外,则显示地图,但是使用上面的代码却没有显示地图,为什么?

If there's no response coming from the ajax post, the callback will never be called. 如果ajax帖子没有响应,则永远不会调用该回调。

A better approach is to use the Promise interface: 更好的方法是使用Promise接口:

var jqxhr = $.post("example.php", function() {
  console.log("success")
}).done(function() {
  // call init_map() on done?
}).fail(function() {
  // call init_map() on error?
}).always(function() {
  // call init_map() regardless the response?
})

Also, you're using google.maps.event.addDomListener to add a listener during window load. 另外,您正在使用google.maps.event.addDomListener在窗口加载期间添加侦听器。 If you're sure that your page is loaded before making the ajax post, you don't need this listener. 如果确定发布ajax帖子之前已加载页面,则不需要此侦听器。 You'll only need to create a new map inside the init_map function. 您只需要在init_map函数内创建一个新地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM