Pass data to callback when asynchronously loading google maps V3

前端 未结 2 1466
不知归路
不知归路 2021-02-13 22:33

I am loading the google maps API asynchronously which allows you to define a callback to execute when the API loads. Is there any way I can pass arguments to the callback?

相关标签:
2条回答
  • How about wrapping your function into some dummy function that passes necessary arguments like:

    function wrapper()
    {
        myCallback(arg1, arg2);
    }
    

    and pass wrapper() as a google maps callback

    0 讨论(0)
  • 2021-02-13 23:19

    I ended up working around the need to pass arguments to the callback.

    I created an object inside my master object to hold information about a specific map. Each map has its own callback defined. It also holds the reference to the initialized map and any additional map specific data that needs to be referenced by the callback.

    /**
     * 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: {}
        }
    }
    

    I modified the mapInit function to store the reference to the map and execute the callback in 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();
    
    
    }
    

    I stored the map name in a data-name attribute on the placeholder element for the map.

    <div id="map" data-name="mainMap"></div>
    
    0 讨论(0)
提交回复
热议问题