简体   繁体   English

Google Maps API加载问题

[英]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? 我正在通过AJAX调用异步加载Google Maps API,但没有收到错误的子屏幕,并且Google API代码正确输出,并且我有有效的经纬度坐标。我正在使用以下代码,任何人都可以对发生什么有什么建议?

<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 上面的整个代码段都是通过ajax调用加载的

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) 当您通过Ajax加载片段时,通常在响应到达时已经加载了窗口,在这种情况下, onload -event已经被触发(并且不会再次触发,将永远不会执行loadScript

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: 正如geocodezip所评论的那样,您的解决方案之所以有效,是因为loadScript将立即执行 ,但是当您要确保窗口已被加载时,请检查文档的readyState属性:

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: 解决了该问题,在用于异步加载地图的Google API文档中,我使用了https://developers.google.com/maps/documentation/javascript/tutorial#asynch页面上的代码,该问题是我正在使用的:

window.onload = loadScript;

When I should have been using: 当我应该一直使用时:

window.onload = loadScript();

You need to provide an API key . 您需要提供一个API密钥

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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