Load BingMaps API on runtime

徘徊边缘 提交于 2020-01-07 03:36:17

问题


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

TypeError: Microsoft.Maps.NetworkCallbacks.f_logCallbackRequest is not a function

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

But I am again running in errors:

jQuery.Deferred exception: n is null k@https://www.bing.com/api/maps/mapcontrol?callback=loadMapScenario:12:7416

In both cases the load_bing_map() function looks like this.

function load_bing_map() {
  var map = new Microsoft.Maps.Map('#mymap', {
    credentials: 'MyKey'
  });
}

The code is executed after the $().ready trigger is fired.

What am I missing?

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.


回答1:


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

You can try it out here: http://bingmapsv8samples.azurewebsites.net/#Lazy%20Loading%20the%20Map



来源:https://stackoverflow.com/questions/45861212/load-bingmaps-api-on-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!