问题
I am loading the Bing Map API script dynamically. When the script finishes loading, I would like to construct my map. The problem is Microsoft
and Microsoft.Maps
are defined, but Microsoft.Maps.Map
is not. I realize that their script will asynchronously load more scripts, but even after waiting 10 seconds for these additional hypothetical scripts, Microsoft.Maps.Map
continues to be undefined. So how do I load their Map
class? I see nothing in their example, that explicitly loads the class.
Javascript (Prototype Framework):
var script = new Element(
'script', {
type: 'text/javascript',
src: 'http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0'
}
);
script.observe(
'load',
function(event) {
console.info(Microsoft);
console.info(Microsoft.Maps);
console.info(Microsoft.Maps.Map);
}
);
document.body.appendChild(script);
Console Output:
>>> Microsoft
Object { Maps={...}}
>>> Microsoft.Maps
Object { Globals={...}}
>>> Microsoft.Maps.Map
undefined
回答1:
cbayram is right that you're looking too early. But specifically you are not using the Bing Map specific way of firing your script once theirs is done loading (onscriptload). We avoid global functions, but AFAIK you really need to use one here.
Try this:
var script = new Element(
'script', {
type: 'text/javascript',
src: 'http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&onscriptload=DrawMap'
}
);
function DrawMap() {
console.info(Microsoft);
console.info(Microsoft.Maps);
console.info(Microsoft.Maps.Map);
}
document.body.appendChild(script);
Not important, but why do you append it to body? I always append it to head.
回答2:
BING Map API's JavaScript file dynamically loads/injects additional JS and CSS files into your page.
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/v7.0/7.0.20121012100453.93/js/en-us/veapicore.js">
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/v7.0/7.0.20121012100453.93/js/en-us/veapidelay.js">
<link rel="stylesheet" type="text/css" rev="stylesheet" href="http://ecn.dev.virtualearth.net/mapcontrol/v7.0/7.0.20121012100453.93/css/en/mapdelay.css">
<link rel="stylesheet" type="text/css" rev="stylesheet" href="http://ecn.dev.virtualearth.net/mapcontrol/v7.0/7.0.20121012100453.93/css/en/mapcontrol.css">
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/v7.0/7.0.20121012100453.93/js/en-us/veapiAnalytics.js">
The Map function/object seems to be created in
http://ecn.dev.virtualearth.net/mapcontrol/v7.0/7.0.20121012100453.93/js/en-us/veapicore.js
EDIT:
Your script.observe runs upon the first (initial) JS file being loaded. It's too early for the Map function as it's instantiated in the veapicore.js that's subsequently loaded by the initial mapcontrol.ashx?v=7.0. You are simply too early in looking for that Map object.
来源:https://stackoverflow.com/questions/12983701/bing-maps-is-undefined-after-loading-their-javascript-file