Download the Google Maps API using AJAX ... but only once for multiple instances

I wrote a little script that loads Google Maps tokens from a JSON file and puts them on a map. The script should be able to handle multiple instances. At the moment, the script looks like this (for testing, I used this JSON file ):

<div id="map" data-file="test.json" style="width: 200px; height: 200px; "></div>
<div id="map2" data-file="test2.json" style="width: 200px; height: 200px; "></div>
<!-- JAVASCRIPT -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    $(function() {
        var googleMaps = function() {
            var $el,
                apiLoaded = false;


            // Init
            // @public
            function init(el) {
                $el = $(el);

                loadData($el.data('file'));
            };


            // Creating a marker and putting it on the map
            // @private
            function createMarker(data) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(data.lat, data.lng),
                    map: map,
                    title: data.title
                });
            }


            // JSON file and API loaded
            // @private
            function ready(data) {
                // Basic settings
                var mapOptions = {
                    center: new google.maps.LatLng(58, 16),
                    zoom: 7,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                map = new google.maps.Map($el[0], mapOptions);

                // Create markers
                $.each(data, function(key, value) {
                    createMarker(value);
                });
            }


            // Load API
            // @private
            function loadAPI(callback) {
                if (typeof google === 'object' && typeof google.maps === 'object') {
                    // API was already loaded
                    if(typeof(callback) === 'function') {
                        callback();
                    }
                } else {
                    // API wasn't loaded yet
                    // Send an AJAX request
                    $.ajax({
                        url: 'http://www.google.com/jsapi/',
                        dataType: "script",
                        success: function() {
                            google.load('maps', '3', {
                                callback: function() {
                                    // Check if callback function is set
                                    if(typeof(callback) === 'function') {
                                        callback();
                                    }
                                }, 
                                other_params: 'sensor=false'
                            });
                        }
                    });
                }
            };


            // Load JSON file
            // @private
            function loadData(file) {
                $.ajax({
                    url: file,
                    success: function(data) {
                        var parsedJson = $.parseJSON(data);
                        loadAPI(function() {
                            ready(parsedJson);
                        });
                    },
                    error: function(request, status, error) {
                        // Error
                        console.log(error);
                    }
                });
            };

            return {
                init: init
            }
        }           
    });
</script>

This works if I have only .init()one instance, for example:

googleMaps().init(document.getElementById('map'));

But it fails as soon as I try a few instances:

googleMaps().init(document.getElementById('map'));
googleMaps().init(document.getElementById('map2'));

, , .loadAPI() google.load() , .loadAPI(), API Google , (Chrome Inspector: Uncaught TypeError: Object # "" (JS API Google)).

, AJAX .loadAPI() ? , true, . - , ?

.

+3
1

.

  • googleMaps(), , , / api google. , api googleMaps ( ).
  • loadAPI, , ajax google . , , , loadAPI, google , ajax.

API Promise . loadAPI , , , googleMaps

        var loadAPIPromise;
        // Load API
        function loadAPI(callback) {
            if (!loadAPIPromise) {
                var deferred = $.Deferred();
                $.ajax({
                    url: 'http://www.google.com/jsapi/',
                    dataType: "script",
                    success: function() {
                        google.load('maps', '3', {
                            callback: function() {
                                deferred.resolve();
                            }, 
                            other_params: 'sensor=false'
                        });
                    }
                });
                loadAPIPromise = deferred.promise();
            }
            loadAPIPromise.done(callback);
        };

jsfiddle http://jsfiddle.net/callado4/gA79R/4/

+5

All Articles