Pass data to callback when asynchronously loading google maps V3

前端 未结 2 1477
不知归路
不知归路 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条回答
  •  攒了一身酷
    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.

提交回复
热议问题