Unable to load google map javascript dynamically

The following tells me that GMap2 is undefined. But the code that GMap2 uses is in the callback.

        $(function() {
        $('#sample').click(function() {
            $.getScript("http://maps.google.com/maps?file=api&v=2&sensor=true&key=API_KEY_HERE", function() {
                var map = new GMap2(document.getElementById("mapTest"));
                map.setCenter(new GLatLng(18, -77.4), 13);
                map.setUIToDefault();

            });
        });
    });

<a id="sample">Click Me</a>
<div id="mapTest" style="width: 200px; height: 100px;"></div>
+3
source share
2 answers

You can go in two ways with this:

1. Continue to use$.getScript :

It seems that you need both a parameter async=2and another callback structure for it to work. My answer is adapted to your code from this great walkthrough here .

<script type="text/javascript">
    function map_callback(){
        var map = new GMap2(document.getElementById("mapTest"));
        map.setCenter(new GLatLng(18, -77.4), 13);
        map.setUIToDefault();
    }

    $(function(){
       $('#sample').click(function(){
          $.getScript("http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;callback=map_callback&amp;async=2&amp;key=API_KEY_HERE");
       }
    }
</script>

2. Use the Google AJAX downloader

Since you are already using the Google Library, why use their downloader to help you:

<script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"></script>
<script type="text/javascript">
   google.load("jquery", "1.3.2");

   google.setOnLoadCallback(function(){
       $('#sample').click(function(){
          google.load("maps", "2", {"callback" : function(){
            var map = new GMap2(document.getElementById("mapTest"));
            map.setCenter(new GLatLng(18, -77.4), 13);
            map.setUIToDefault();
          } });
       }
   }, true); // Passing true, though undocumented, is supposed to work like jQuery DOM ready
</script>
+4

, ? GMAP, ...

if (GBrowserIsCompatible()) 
+1

Source: https://habr.com/ru/post/1727729/


All Articles