Heim > Fragen und Antworten > Hauptteil
我想用如下方式引入百度地图服务,请问为什么出错?
angular.module('bmap',[])
.factory('bmapService', ['$document', '$q', '$rootScope',
function($document, $q, $rootScope) {
var map = $q.defer();
function onScriptLoad() {
// Load client in the browser
$rootScope.$apply(function() { map.resolve(window.bmap); });
}
// Create a script tag with d3 as the source
// and call our onScriptLoad callback when it
// has been loaded
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = 'http://api.map.baidu.com/api?type=quick&ak=XXXX&v=1.0';
scriptTag.onreadystatechange = function () {
if (this.readyState == 'complete') onScriptLoad();
};
scriptTag.onload = onScriptLoad;
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);
return {
bmap: function() { return map.promise; }
};
}]);
使用地图服务(app依赖项已包含bmap
,以下代码为使用服务的controller)
app.controller('backup',function($rootScope,bmapService){
$rootScope.gotoBackup();
map = new bmapService.bmap()
.BMap.Map('map');
})
百度给出的使用示例:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body, html,#l-map {width: 100%;height: 100%;overflow: hidden;margin:0;}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?type=quick&ak=您的密钥&v=1.0"></script>
<title>显示地图</title>
</head>
<body>
<p id="l-map"></p>
</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("l-map");
map.centerAndZoom(new BMap.Point(116.404, 39.915), 14);
</script>
高洛峰2017-05-15 16:53:38
你的bmapService.bmap()返回的是一个promise对象,你要对promise对象使用then(function(){}),在回调方法中才能使用加载完成的地图API