2016-12-01 35 views
0

我正在尝试在Aurelia SPA中使用BingMaps。 我所做的是将BingMaps脚本标记添加到索引页面的头部分。像这样:如何等待BingMaps在Aurelia中加载

<head> 
    <meta charset="utf-8"> 
    <script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=release'></script> 
</head> 

然后,我有这样的地图模板和地图控制器:

map.html

<template> 
    <div id='mainMap' style='width: 100vw; height: 100vh;'></div> 
</template> 

map.ts

export class Map 
{ 
    map:Microsoft.Maps.Map; 

    attached(){ 
     this.map = new Microsoft.Maps.Map('#mainMap', {credentials: myKey}); 
     this.map.setView({center: new Microsoft.Maps.Location(45.093,14.114), zoom:15}); 
    } 
} 

现在的我, m使用Aurelia Typescript WebPack Skeleton作为我的应用程序。 如果我运行该应用程序并单击地图菜单链接,我创建了所有正确的作品和我显示的地图。 但是,如果我在PRES的浏览器中刷新奥里利亚抛出异常:

Unhandled rejection TypeError: Cannot read property 'prototype' of null at k (https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:7096) at h (https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:6285) at e (https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:1106) at t.l [as instance] (https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:161) at h (https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:6042) at e (https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:1106) at t.l [as instance] (https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:161) at new Microsoft.Maps.Map (https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:13:4304) at Map.attached (http://localhost:9000/app.bundle.js:28421:20) at Controller.attached

像地图脚本运行在地图控制器连接的方法之前尚未加载。 如何在运行Attached方法之前告诉Aurelia等待地图脚本加载?

+1

这不是您的问题的答案,只是最佳做法。你不应该在文件名中使用大写字母。我建议将'Map.html'改为'map.html'和'Map.ts'为'map.ts'。这是为了更好的兼容性。 Aurelia也对命名约定做了一些假设,大写字母可能会影响功能。 – LStarky

+0

同意,更改。 – Luka

回答

1

您有两种选择。第一种方法是在地图脚本URL中添加一个回调参数,并在地图脚本加载完成后传入函数的名称进行调用。例如:

<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?callback=LoadMap' async defer></script> 

请注意,您不需要说出你想要的发布分支,也就是默认分支的地图控件加载。

第二个选项有点复杂,但帮助了其他不想使用回调方法的人。此方法由监视Microsoft.Maps名称空间并等待它可用。这可以使用超时完成。例如:

function LoadMap(){ 
    if(typeof Microsoft !== undefined && typeof Microsoft.Maps !== undefined){ 
     //Map API available add your map load code. 
    } else { 
     setTimeout(LoadMap, 100); 
    } 
} 
+0

谢谢。这会做 – Luka