问题描述
我正在尝试在JavaScript文件的运行时加载Bing Maps API.这是我到目前为止基于 this所得到的.
I am trying to load the Bing Maps API during runtime of my JavaScript file. Here is what i have got so far, based on this.
var bingmap_link = 'https://www.bing.com/api/maps/mapcontrol?callback=loadMapScenario';
$.when(
$.getScript(bingmap_link),
$.Deferred(function( deferred ){
$( deferred.resolve );
})
)
.done(function() {
console.log("done");
load_bing_map();
});
但是我会收到以下错误消息
But i will get the following error
所以我尝试了另一种尝试:
So I tried another attempt:
$('head').append('<script type="text/javascript" src="https://www.bing.com/api/maps/mapcontrol?callback=loadMapScenario" async defer></script>');
load_bing_map();
但是我再次出现错误:
在两种情况下,load_bing_map()
函数都是这样的.
In both cases the load_bing_map()
function looks like this.
function load_bing_map() {
var map = new Microsoft.Maps.Map('#mymap', {
credentials: 'MyKey'
});
}
触发$().ready
触发器后执行代码.
The code is executed after the $().ready
trigger is fired.
我想念什么?
最后,我不需要像这样的解决方案
Finally I do not need a solution like
<head>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=loadMapScenario' async defer></script>
</heady>
我只能在运行时这样做.
I can only do it during runtime.
推荐答案
您正在地图脚本URL中指定一个回调函数,但代码中没有使用该名称的函数.这是导致您看到的错误.此外,您拥有的代码无法按原样工作.地图控件异步加载大量资源.这样一来,您便可以使用完了的功能,只有初始的javascript文件已加载,其他资源均未加载,因此map API尚不可用.以下代码示例显示了如何延迟加载地图API: https://github.com/Microsoft/BingMapsV8CodeSamples/blob/master/Samples/Map/Lazy%20Loading%20the%20Map.html
You are specifying a callback function in the map script URL but don't have a function with that name in your code. That is causing the error you seeing. Additionally, the code you have will not work as is. The map control loads a bunch of resources asynchronously. As such, then the done function in your could is reached, only the initial javascript file has been loaded, none of the other resources has, so the map API is not available yet. Here is a code sample that shows how to lazy load the map API: https://github.com/Microsoft/BingMapsV8CodeSamples/blob/master/Samples/Map/Lazy%20Loading%20the%20Map.html
您可以在这里尝试: http://bingmapsv8samples.azurewebsites.net /#Lazy%20Loading%20the%20Map
这篇关于在运行时加载BingMaps API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!