2017-07-07 67 views
0

好的,我已经找到了解决方案,我相信有人会说这是一个重复的话题,但我很困惑,为什么这是行不通的。bing map v7到v8迁移 - 脚本导入问题

这是我的代码的一个基本的例子,现在

main.html中

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <script type="text/javascript" src="main.js"></script> 
</head> 

<body> 
    <div id="myMap" style="position:relative;width:600px;height:400px;"></div> 
</body> 
<script> 
    var url = 
    //'http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=GetMap'; 
    'https://www.bing.com/mapspreview/sdk/mapcontrol'; 
    loadScript(url, test_function); 
    function test_function() { 
     console.log('inside test_function before map'); 
     map = new Microsoft.Maps.Map('#myMap', { 
      credentials: 'My Bing Maps Key'}); 
     console.log('inside test_function after map'); 
    }; 
</script> 

</html> 

main.js

function loadScript(url, callback){ 

    var script = document.createElement("script") 
    script.type = "text/javascript"; 
    script.async = true; 
    script.defer = true; 

    if (script.readyState){ //IE 
     console.log('inside IE block'); 
     script.onreadystatechange = function(){ 
      if (script.readyState == "loaded" || 
        script.readyState == "complete"){ 
       script.onreadystatechange = null; 
       callback(); 
      } 
     }; 
    } else { //Others 
     console.log('inside Other block'); 
     script.onload = function(){ 
      callback(); 
     }; 
    } 

    script.src = url; 
    document.getElementsByTagName("head")[0].appendChild(script); 
} 

控制台输出

main.js:18 inside Other block 
main.html:17 inside test_function before map 
mapcontrol:11 Uncaught TypeError: Cannot read property 'prototype' of null 
    at k (mapcontrol:11) 
    at n.h [as create] (mapcontrol:11) 
    at e (mapcontrol:11) 
    at t.l [as instance] (mapcontrol:11) 
    at n.h [as create] (mapcontrol:11) 
    at e (mapcontrol:11) 
    at t.l [as instance] (mapcontrol:11) 
    at new Microsoft.Maps.Map (mapcontrol:13) 
    at test_function (main.html:18) 
    at HTMLScriptElement.script.onload (main.js:20) 

我可以得到一个基本的示例工作,但是当我尝试执行这种创建脚本元素并追加它的方法时,我什么也得不到。由于这是它在更大的应用程序中实现的方式,因此它来自v7,我不想重新构建它。

我尝试过像jQuery getScript之类的东西,而不是什么。

请让我知道你的想法!谢谢。

回答

1

我能想到的第一件事就是您应该从公开发布的问题中删除您的凭据。只是一个想法。

其次,错误是由于试图在加载地图之前与地图交互。

我个人从来没有见过用这种方式加载过的脚本,但我想它是有效的 - 至少在某些情况下,但可能不是这个。我假设你有这样做的理由。

无论如何,由于缺乏对此的了解,我只能假设发生的事情是脚本正在被加载,并且您的回调(test_function)正在被调用,因为代码似乎暗示了它的作用。

然而,脚本被加载并Bing地图被装载的是,我怀疑,两种不同的东西在这种情况下。

您最初注释掉了&callback=GetMap的网址是异步加载Bing地图的文档化方式。一旦Bing Maps加载完成,您的GetMap函数将被调用。有了这个特定的代码,callback=test_function将是你想要的。

因此test_function应该由Bing地图本身启动,而不是通过脚本加载函数传递(再次假设它是如何工作的)。我想,加载函数实际上并不想做其他任何事情,除非得到该脚本,所以没有回调方法; Bing地图会为您处理。

这是你的工作Plunker