javascript - 异步加载 google maps V3 时将数据传递给回调

标签 javascript google-maps-api-3

我是loading the google maps API asynchronously它允许您定义回调以在 API 加载时执行。有什么方法可以将参数传递给回调?

编辑:

这是我正在使用的代码。我有一个名为 master 的全局对象,用于存储以下函数。

/**
 * Load the Google Maps API
 * https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API
 */
loadGoogleMaps: function(){
    var googleMaps = document.createElement("script");
    googleMaps.type = "text/javascript";
    googleMaps.src = "http://maps.googleapis.com/maps/api/js?key=[MYAPIKEY]&sensor=false&callback=master.mapInit";
    document.body.appendChild(googleMaps);
}

我希望能够将位置数组传递到 mapInit 中,这样我就可以在 map 初始化时将标记添加到 map 中。我还希望能够全局访问对 map 的引用,以便在创建 map 后对其进行修改。

/**
 * Initialize the map
 */
mapInit: function(){

    // Default map options
    var mapOptions = {
        zoom: 4,
        center: new google.maps.LatLng( 40, -95 ),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    // Create map
    var map = new google.maps.Map( document.getElementById("map"), mapOptions );

}

最佳答案

我最终解决了将参数传递给回调的需要。

我在 master 对象中创建了一个对象来保存有关特定 map 的信息。每个 map 都有自己定义的回调。它还包含对初始化 map 的引用以及回调需要引用的任何其他 map 特定数据。

/**
 * Map listing
 */
mapList: {
    mainMap: {
        map: "",
        callback: function(){

            for( var i = 0, length = this.locations.length; i < length; i++ ){

                master.placeMapMarker( this.locations[i], this );

            }

        },
        prevInfoWindow: "",
        locations: {}
    }
}

我修改了 mapInit 函数以存储对 map 的引用并在 master.mapList.mainMap 中执行回调。

/**
 * Initialize the map
 */
mapInit: function(){


    // Default map options
    var mapOptions = {
        zoom: 4,
        center: new google.maps.LatLng( 40, -95 ),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    // Create map
    var mapName = $("#map").data("name");
    var map = this.mapList[mapName].map = new google.maps.Map( document.getElementById("map"), mapOptions );

    this.mapList[mapName].callback();


}

我将 map 名称存储在 map 占位符元素的 data-name 属性中。

<div id="map" data-name="mainMap"></div>

关于javascript - 异步加载 google maps V3 时将数据传递给回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11129033/

相关文章:

javascript - 如何将 HTMLButtonElement 对象转换为 html 按钮?

javascript - 使用 jest 运行测试时如何修复 "Test suite failed to run"

javascript - 在函数内传递 JSON 对象

javascript - 在我缩放到的多边形中显示标记

javascript - 以间隔更新多个信息窗口

javascript - Jquery 脚本中的 Google 区域偏差

javascript - 使用 Framework7 时 Cordova 插件不工作

javascript - Promise.all, webdriver.promise.all, protractor.promise.all 的区别

android - 将总数显示为多个图钉的文本,一个图钉在 android map 中的同一位置

javascript - 如何根据缩放谷歌地图api计算圆半径