如何等待在Aurelia中加载BingMaps

时间:2016-12-01 09:05:56

标签: google-chrome typescript webpack bing-maps aurelia

我正在尝试在Aurelia SPA中使用BingMaps。 我所做的是将BingMaps脚本标记添加到Index页面的Head部分。像这样:

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

然后我有一个Map模板和Map控制器,如下所示:

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

现在,我正在为我的应用程序使用Aurelia Typescript WebPack Skeleton。 如果我运行应用程序并单击地图菜单链接,我创建的所有工作正常,我显示的地图。 但如果我在浏览器中使用Refresh,Aurelia会抛出异常:

  

未处理拒绝TypeError:无法读取null的属性'prototype'       在k(https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:7096)       在h(https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:6285)       在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)       在h(https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:11:6042)       在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)       在新的Microsoft.Maps.Map(https://www.bing.com/mapspreview/sdk/mapcontrol?branch=release:13:4304)       在Map.attached(http://localhost:9000/app.bundle.js:28421:20)       在Controller.attached

就像在运行Map控制器中的Attached方法之前尚未加载Map脚本一样。 在运行Attached方法之前,如何告诉Aurelia等待加载地图脚本?

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

那么您需要等待两个事件,第一个当然是脚本的加载,然后您需要等待Microsoft脚本加载其API,为此目的,存在回调参数:我建议使用jquery对于第一个任务,因为它很容易转化为承诺,即:

const _BING_MAPS_URL = 'https//www.bing.com/api/maps/mapcontrol?';
const _DEFAULT_CONFIG = $.params({
  key: 'yourkey',
  callback: 'globalScopedCallback'
});

loadBingMaps() {
  const callbackInvoked = new Promise((resolve) => {
     window.globalScopedCallback = resolve;
  });
  const scriptLoaded = new Promise((resolve, reject) => {
    $.getScript(_BING_MAPS_URL + _DEFAULT_CONFIG).done(resolve).fail(reject);
  });
  // You can add here more promises loading modules, and anything you need.
  return Promise.all([callbackInvoked, scriptLoaded]);
}
// Now you are sure everything is loaded
loadBingMaps().then(doYourAwesomeStuff);