1

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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.