Dynamically Loading Google Maps api's

2020-03-01 18:31发布

Im trying to load the google maps api's dynamically. I'm using the following code:

var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.google.com/jsapi?key=<MY_KEY>;
head.appendChild(script);

but when trying to create the map

map = new GMap2(document.getElementById("map"));

or

map = new google.maps.Map2(document.getElementById("map"));

I'm getting an error that google (or GMap2) is undefined.

4条回答
聊天终结者
2楼-- · 2020-03-01 19:11

Make sure that you aren't instantiating the map before the Javascript has finished loading.

Also, If you want to use the AJAX API loader, you need to do it like this:

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

    // Call this function when the page has been loaded
    function initialize() {
        var map = new google.maps.Map2(document.getElementById("map"));
        map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
    }
    google.setOnLoadCallback(initialize);
</script>

Otherwise, just use the regular Maps API script source:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=abcdefg&sensor=true_or_false" type="text/javascript"></script>
查看更多
▲ chillily
3楼-- · 2020-03-01 19:13

You can do this. You can add a callback function name in the url. It'll be called when the API gets loaded. That callback function must be accessible in the document's scope.

I did that some time ago by triggering a custom event on the window with jQuery: http://jsfiddle.net/fZqqW/5/

used "http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback"

window.gMapsCallback = function(){
    $(window).trigger('gMapsLoaded');
}

$(document).ready((function(){
    function initialize(){
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(-34.397, 150.644),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
    }
    function loadGoogleMaps(){
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type","text/javascript");
        script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    }
    $(window).bind('gMapsLoaded', initialize);
    loadGoogleMaps();
})());​

Asynchronously Loading the API

You may wish to load the Maps API JavaScript code after your page has finished loading, or on demand. To do so, you can inject your own tag in response to a window.onload event or a function call, but you need to additionally instruct the Maps JavaScript API bootstrap to delay execution of your application code until the Maps JavaScript API code is fully loaded. You may do so using the callback parameter, which takes as an argument the function to execute upon completing loading the API.

The following code instructs the application to load the Maps API after the page has fully loaded (using window.onload) and write the Maps JavaScript API into a tag within the page. Additionally, we instruct the API to only execute the initialize() function after the API has fully loaded by passing callback=initialize to the Maps

See HERE : https://developers.google.com/maps/documentation/javascript/tutorial

查看更多
劳资没心,怎么记你
4楼-- · 2020-03-01 19:23

I've done it like so... this example uses jQuery and google map v3.x

$.getScript("http://maps.google.com/maps/api/js?sensor=true&region=nz&async=2&callback=MapApiLoaded", function () {});

function MapApiLoaded() {
    //.... put your map setup code here: new google.maps.Map(...) etc
}
查看更多
姐就是有狂的资本
5楼-- · 2020-03-01 19:29

This works for me:

    const myApiKey = `12345`;
    const lat = -34.397;
    const lng = 150.644;
    const zoom = 8;

    const parentElement = document.getElementById(`map`); // a <div>
    const script = document.createElement(`script`);
    script.src = `https://maps.googleapis.com/maps/api/js?key=${myApiKey}`;
    script.async = true;
    script.defer = true;
    script.onload = function () {
        new google.maps.Map(parentElement, {
            center: {lat, lng},
            zoom
        });
    };
    parentElement.insertBefore(script, null);
查看更多
登录 后发表回答