简体   繁体   中英

Google Maps API Loading Issue

I'm asynchronously loading the Google Maps API via an AJAX call and I'm getting no error son screen and the Google API code is outputting correctly and I have valid lat/lng coords., I'm using the below code, can anyone suggest any ideas as to what is going on?

<script type="text/javascript">
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng({lat}, {lng}),
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}           
function loadScript()
{
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.googleapis.com/maps/api/js?key={api_key}&sensor=false&callback=initialize";
    document.body.appendChild(script);
}
window.onload = loadScript;
</script>
<div id="map-canvas" class="map-canvas"></div>

The whole code snippet above is loaded in via an ajax call

When you load the fragment via ajax, at the time when the response arrives usually the window has already been loaded, in this case the onload -event already has been fired(and will not fire again, loadScript will never be executed)

As commented by geocodezip your solution works because loadScript will be executed immediately , but when you want to be sure that the window has already been loaded, check the readyState-property of the document:

if(document.readyState==='complete'){
  loadScript();
}else{
  window.onload = loadScript;
}

Solved it, on the Google API documentation for asynchronously loading the map I used the code as it is on the page https://developers.google.com/maps/documentation/javascript/tutorial#asynch , the issue was I was using:

window.onload = loadScript;

When I should have been using:

window.onload = loadScript();

You need to provide an API key .

function loadScript()
{
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.googleapis.com/maps/api/js?key=api_key&sensor=false&callback=initialize";
    script.src.replace('api_key', "3d73a8acf7ab7f466fb7c9da390df68c"); //  This is not a real api key
    document.body.appendChild(script);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM