cari

Rumah  >  Soal Jawab  >  teks badan

angular.js - 用angularjs的service封装百度地图api出错,请问原因?

我想用如下方式引入百度地图服务,请问为什么出错?

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>
我想大声告诉你我想大声告诉你2743 hari yang lalu520

membalas semua(1)saya akan balas

  • 高洛峰

    高洛峰2017-05-15 16:53:38

    bmapService.bmap() anda mengembalikan objek promise Anda perlu menggunakan then(function(){}) pada objek promise untuk menggunakan API peta yang dimuatkan dalam kaedah panggil balik

    balas
    0
  • Batalbalas