今天在测试高德地图的兼容性时,遇到了一个关于js函数的问题,由于之前没怎么学过js,所以找不出问题所在,在此有请各位热心大神帮帮看下是哪里出问题了:
//加载地理编码插件
function getMGeocoder(){
var MGeocoder = null;
AMap.service(["AMap.Geocoder"], function() {
MGeocoder = new AMap.Geocoder({
city:"广州市",
radius: 3000,// 逆地理编码时,以给定坐标为中心点
extensions: "base" // 返回地址描述以及附近兴趣点和道路信息,默认"base"
});
});
console.info('MGeocoder1:'+MGeocoder);
return MGeocoder;
}
就是上面这段代码,在谷歌浏览器可以输出MGeocoder是个object,但是在IE8中输出了null。不知道是IE8中对js的兼容性问题还是本身的代码问题,求解!
高德地图API没写是不是兼容IE8吗??
AMap.service(["AMap.Geocoder"]是异步的,有可能还没执行回调给MGeocoder 赋值当然是null
异步传输数据的,不能return返回异步返回的值,要不会报错,要是要将用使用异步回传数据的代码做成回调形式来调用
function getMGeocoder(callback) {
var MGeocoder = null;
AMap.service(["AMap.Geocoder"], function () {
MGeocoder = new AMap.Geocoder({
city: "广州市",
radius: 3000,// 逆地理编码时,以给定坐标为中心点
extensions: "base" // 返回地址描述以及附近兴趣点和道路信息,默认"base"
});
callback(MGeocoder)
});
// console.info('MGeocoder1:' + MGeocoder);
//return MGeocoder;
}
getMGeocoder(function (MGeocoder) {
console.log(MGeocoder)
})