rdh*_*aut 3 cdn bing-maps typescript vuejs2
如何在 vue js 应用程序中使用 bing maps api 来显示地图?
注意:我使用 Bing 地图 V8 和 vuejs 2.5.17。
这是我的模板
<template>
<div id="map"></div>
</template>
Run Code Online (Sandbox Code Playgroud)
这是我的风格
<style lang="scss" scoped>
#map {
height: 300px;
width: 500px;
}
</style>
Run Code Online (Sandbox Code Playgroud)
这是我的脚本部分(我使用基于类的对象组件)
mounted() {
let mapElement: HTMLElement = <HTMLElement>document.getElementById("map")
var map = new Microsoft.Maps.Map(mapElement, {
credentials: [API_KEY]
});
}
Run Code Online (Sandbox Code Playgroud)
这就是我在我的应用程序中包含来自 cdn 的外部脚本的方式。经过一番研究,我发现并尝试了以下 2 个选项
选项 1:我已将脚本直接包含在我的 index.html 文件中:
<!-- index.html -->
...
<head>
...
<script src="https://www.bing.com/api/maps/mapcontrol?key=[API_KEY]" async defer></script>
</head>
Run Code Online (Sandbox Code Playgroud)
选项 2:我以编程方式从我的组件中的安装方法中注入文档中的脚本,如下所示
mounted() {
// Add programmaticaly the external Bing maps api script
var scriptTag = document.createElement("script");
scriptTag.src = "https://www.bing.com/api/maps/mapcontrol";
scriptTag.id = "bingApiMaps";
// Inject the dynamic script in the DOM
document.head.appendChild(scriptTag);
...
}
Run Code Online (Sandbox Code Playgroud)
在两者中,我都有以下错误,我不明白为什么:
[Vue warn]: Error in mounted hook: "ReferenceError: Microsoft is not defined"
Run Code Online (Sandbox Code Playgroud)
小智 5
我已经转录了 rdhainaut 对 JavaScript 的回答:
mounted: function() {
if (document.getElementById("scriptBingMaps")) {
return; // already loaded
}
// Add a global function for the callback from Bing Maps api
window.OnLoadBingMapsApi = () => this.InitMap();
// Add programmaticaly the external Bing maps api script
var scriptTag = document.createElement("script");
scriptTag.src = "https://www.bing.com/api/maps/mapcontrol?callback=OnLoadBingMapsApi&key=[BING_API_KEY]";
scriptTag.id = "scriptBingMaps";
// Inject the dynamic script in the DOM
document.head.appendChild(scriptTag);
},
methods: {
InitMap: function() {
var mapElement = this.$refs.myMap;
this.map = new Microsoft.Maps.Map(mapElement, {
mapTypeId: Microsoft.Maps.MapTypeId.aerial,
zoom: 15,
maxZoom: 21,
//minZoom: 15,
center: new Microsoft.Maps.Location(52.7759872, -1.5119702),
maxNetworkLinkDepth: 3
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1529 次 |
| 最近记录: |